视网膜的Swift CGContext

时间:2018-07-09 19:12:32

标签: swift cgcontext cgimage retina

我有一个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函数,我认为它不起作用。

1 个答案:

答案 0 :(得分:2)

我想你想要

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

和:

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

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