带有视网膜的 Swift CGContext

标签 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 函数,它不会起作用。

最佳答案

我想你想要:

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

和:

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

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

关于带有视网膜的 Swift CGContext,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51252568/

相关文章:

swift - 使用组合的自定义更改运算符

iphone - CGContext 使用两个不透明的 UIColor 绘制

objective-c - 绘制虚线和实线

ios - 使用坐标验证像素 (iOS)

objective-c - UIImageView、CGImage 和 Retina Art

ios - 使用 UIImages 创建 gif

swift - 从 AppleScript 调用 Swift 方法

ios - 类型 'UIViewController' 的值没有成员 'mapView'

ios - 在 Swift 中将 .plist 数据读入字典

ios - CGContext绘制两个相邻的菱形产生了很细的间隙,如何减少它?