在 2x 设备上,使用手动创建的 shadowRadius = r 和 shadowOffset = (x, y) 渲染 CALayer >CGContext 使用 CALayer.render(in 产生一个带有 shadowRadius = r/2 和 shadowOffset = (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
- 色彩空间
- 位图信息
- ctm
- 插值质量
这里是 sample app .
Best Answer-推荐答案 strong>
In the Drawing and Printing Guide for iOS
它说明了以下关于阴影的内容:
Shadows
The direction a shadow falls from its object is specified by an offset
value, and the meaning of that offset is a convention of a drawing
framework. In UIKit, positive x and y offsets make a shadow go down
and to the right of an object. In Core Graphics, positive x and y
offsets make a shadow go up and to the right of an object. Flipping
the CTM to align an object with the default coordinate system of UIKit
does not affect the object’s shadow, and so a shadow does not
correctly track its object. To get it to track correctly, you must
modify the offset values appropriately for the current coordinate
system.
我目前在我正在开发的应用程序中面临同样的问题。似乎您可能需要手动设置阴影偏移量。
关于ios - 为什么在手动创建的 CGContext 中 CALayer 阴影渲染不正确?,我们在Stack Overflow上找到一个类似的问题:
https://stackoverflow.com/questions/43332941/
|