为什么CALayer的影子呈现在手动创建CGContext上不正确的?

问题描述 投票:2回答:1

上的2倍设备,使用CALayer在手动创建shadowRadius = r呈现与shadowOffset = (x, y)CGContext一个CALayer.render(in:)产生具有shadowRadius = r/2shadowOffset = (x/2, -y/2)阴影,仿佛在即使其已经正确设置的初始状态变换矩阵没有设置和静止。

如果上下文设置使用UIGraphicsBeginImageContextWithOptions的结果是正确的。

即使我基于与UIGraphicsBeginImageContextWithOptions结果产生的环境中创建我自己的背景仍然是错误的。

// Manually created context produces wrong shadow.
let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.premultipliedFirst.rawValue | CGBitmapInfo.byteOrder32Little.rawValue)
if let ctx1 = CGContext(data: nil, width: Int(view.bounds.width * UIScreen.main.scale), height: Int(view.bounds.height * UIScreen.main.scale), bitsPerComponent: 8, bytesPerRow: Int(4 * view.bounds.width * UIScreen.main.scale), space: CGColorSpaceCreateDeviceRGB(), bitmapInfo: bitmapInfo.rawValue) {
    ctx1.scaleBy(x: UIScreen.main.scale, y: -UIScreen.main.scale)
    ctx1.translateBy(x: 0, y: -view.bounds.height)

    view.layer.render(in: ctx1)
    guard let image = ctx1.makeImage() else {
        return
    }
    UIImageWriteToSavedPhotosAlbum(UIImage(cgImage: image), nil, nil, nil)
}

// Context created using UIGraphicsBeginImageContextWithOptions produces correct shadow.
UIGraphicsBeginImageContextWithOptions(view.bounds.size, false, UIScreen.main.scale)
if let ctx2 = UIGraphicsGetCurrentContext() {
    view.layer.render(in: ctx2)
    guard let image = ctx2.makeImage() else {
        return
    }
    UIImageWriteToSavedPhotosAlbum(UIImage(cgImage: image), nil, nil, nil)

    // Manually created context with configurations copied from the "good" context still produces wrong shadow.
    if let ctx3 = CGContext(data: nil, width: ctx2.width, height: ctx2.height, bitsPerComponent: ctx2.bitsPerComponent, bytesPerRow: ctx2.bytesPerRow, space: ctx2.colorSpace!, bitmapInfo: ctx2.bitmapInfo.rawValue) {
        ctx3.concatenate(ctx2.ctm)

        view.layer.render(in: ctx3)
        guard let image = ctx3.makeImage() else {
            return
        }
        UIImageWriteToSavedPhotosAlbum(UIImage(cgImage: image), nil, nil, nil)
    }
}

我比较,并确保所有的3个上下文的这些配置都是相同的:

  • 宽度
  • 高度
  • bitsPerComponent
  • bytesPerRow
  • 色彩空间
  • BITMAPINFO
  • CTM
  • 插值质量

这里是sample app

ios core-graphics calayer cgcontext
1个回答
0
投票

In the Drawing and Printing Guide for iOS

它指出有关的阴影下:

阴影

一个阴影,从物体落入方向由偏移值指定的,并且该偏移的意思是一个绘图框架的公约。 UIKit中,正x和y偏移使阴影下去,到对象的权利。核芯显卡,积极x和y偏移使阴影上去同一个对象的右侧。翻转CTM对齐用默认的对象坐标的UIKit的系统不影响对象的影子,所以影子不正确地跟踪它的对象。为了得到它正确地跟踪,你必须相应地修改偏移值的当前坐标系。

我目前面临着同样的问题,我的工作在一个应用程序。它好像你可能需要手动设置阴影偏移。

© www.soinside.com 2019 - 2024. All rights reserved.