【问题标题】:Swift CGContext with retina带有视网膜的 Swift CGContext
【发布时间】:2018-07-09 19:12:31
【问题描述】:

我有一个 UIImage 扩展程序,它可以更改我在某处提取的图像的颜色。问题是它在为图像着色后会降低分辨率。我已经看到了基于此的其他答案,但我不确定如何使其适应在这种情况下渲染视网膜图像:

extension UIImage {

    func maskWithColor(color: UIColor) -> UIImage? {
        let maskImage = cgImage!

        let width = size.width
        let height = size.height
        let bounds = CGRect(x: 0, y: 0, width: width, height: height)

        let colorSpace = CGColorSpaceCreateDeviceRGB()
        let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.premultipliedLast.rawValue)

        let context = CGContext(data: nil, width: Int(width), height: Int(height), bitsPerComponent: 8, bytesPerRow: 0, space: colorSpace, bitmapInfo: bitmapInfo.rawValue)!

        context.clip(to: bounds, mask: maskImage)
        context.setFillColor(color.cgColor)
        context.fill(bounds)

        if let cgImage = context.makeImage() {
            let coloredImage = UIImage(cgImage: cgImage)
            return coloredImage
        } else {
            return nil
        }
    }

}

我见过有人使用 UIGraphicsBeginImageContextWithOptions 并将其比例设置到主屏幕,但如果我使用 CGContext 函数,我认为它不起作用。

【问题讨论】:

  • 拒绝投票和关闭请求在没有解释的情况下根本没有帮助。

标签: swift cgcontext cgimage retina


【解决方案1】:

我想你想要:

    let width = size.width * scale
    let height = size.height * scale

和:

        let coloredImage = UIImage(cgImage: cgImage, scale:scale, orientation:.up)

(您可能需要使用imageOrientation 而不是.up。)

【讨论】:

  • 比例应该是 UIScreen.main.scale 吗?因为这会让它变得更大。
  • 在我的原始代码中,它绘制了正确的大小,而不是视网膜,所以它明显像素化了。
  • scale 应该是此扩展所作用的UIImage 对象的scale 属性。问题是CGContext 使用像素,而不是“点”。 UIImagesize 以点为单位,而不是像素。乘以scale 得到像素,这些像素适合创建与原始像素数相同的CGContext。然后,在创建新的UIImage 时传递scale 让它知道它的大小(以点为单位)应该不同于CGImage 的大小(以像素为单位)。有可能应该是1.0 / scale
  • 做到了!将高度和宽度的比例因子设置为 2 很重要,cgImage 的比例也设置为相同的因子。它在我的脑海中并没有完全转化,因为更大的比例因子使它更小,但更高的清晰度。
  • 比例因子是每点有多少像素。在第一种情况下(将宽度和高度乘以比例),您正在从点转换为像素。创建新的UIImage 时,您是在告诉系统如何将CGImage 的大小(以像素为单位)转换为UIImage 的大小(以磅为单位)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-03-19
  • 1970-01-01
  • 1970-01-01
  • 2013-02-10
  • 1970-01-01
  • 2012-10-24
  • 2012-12-16
相关资源
最近更新 更多