绘制成缩放的 CGContext 会产生全白图像
Drawing into a scaled CGContext results in all-white image
如果我将图像绘制到 CGContext 中,当我稍后用它制作图像时,它会按预期工作。但是当我想通过将 X 轴缩放 -1 来镜像此图像时,生成图像的相同代码会生成全白图像 - 即。不起作用。我错过了什么?
let context = CGContext(data: nil, width: Int(aspectFitSize.width), height: Int(aspectFitSize.height), bitsPerComponent: bitsPerComponent, bytesPerRow: bytesPerRow, space: colorSpace, bitmapInfo: bitmapInfo.rawValue)
context.scaleBy(x: -1, y: 1) // <-- this line causes the problem; it's fine without it, but I want to mirror the image...
context.draw(cgImage, in: CGRect.init(origin: .zero, size: aspectFitSize))
let image = context.makeImage()
您已将图像沿 Y 轴镜像。所以点 (1, 0) 现在是 (-1, 0)。这意味着一切(几乎可以肯定)都在边界之外,在 X 平面的负半部分。
如果您希望 "the right hand edge" 为零,您还需要将上下文翻译成屏幕宽度。类似于:
context.translateBy(x: bounds.width, y:0)
(未经测试)
如果我将图像绘制到 CGContext 中,当我稍后用它制作图像时,它会按预期工作。但是当我想通过将 X 轴缩放 -1 来镜像此图像时,生成图像的相同代码会生成全白图像 - 即。不起作用。我错过了什么?
let context = CGContext(data: nil, width: Int(aspectFitSize.width), height: Int(aspectFitSize.height), bitsPerComponent: bitsPerComponent, bytesPerRow: bytesPerRow, space: colorSpace, bitmapInfo: bitmapInfo.rawValue)
context.scaleBy(x: -1, y: 1) // <-- this line causes the problem; it's fine without it, but I want to mirror the image...
context.draw(cgImage, in: CGRect.init(origin: .zero, size: aspectFitSize))
let image = context.makeImage()
您已将图像沿 Y 轴镜像。所以点 (1, 0) 现在是 (-1, 0)。这意味着一切(几乎可以肯定)都在边界之外,在 X 平面的负半部分。
如果您希望 "the right hand edge" 为零,您还需要将上下文翻译成屏幕宽度。类似于:
context.translateBy(x: bounds.width, y:0)
(未经测试)