Swift 视网膜疾患
我有一个UIImage扩展,可以改变我在某处拍摄的图像的颜色。问题是它在给图像上色后会降低分辨率。我已经看到了基于此的其他答案,但我不确定如何将其应用于在这种情况下渲染视网膜图像:Swift 视网膜疾患,swift,cgcontext,cgimage,retina,Swift,Cgcontext,Cgimage,Retina,我有一个UIImage扩展,可以改变我在某处拍摄的图像的颜色。问题是它在给图像上色后会降低分辨率。我已经看到了基于此的其他答案,但我不确定如何将其应用于在这种情况下渲染视网膜图像: extension UIImage { func maskWithColor(color: UIColor) -> UIImage? { let maskImage = cgImage! let width = size.width let heigh
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
以及:
(您可能需要使用
imageOrientation
而不是.up
)比例应该是UIScreen.main.scale吗?因为这使它更大。在我的原始代码中,它绘制了正确的大小,而不是视网膜,因此它是明显的像素化。scale
应该是UIImage
对象的scale
属性,该扩展正在其上运行。问题在于CGContext
使用像素,而不是“点”。ui图像
的大小
以点为单位,而不是以像素为单位。乘以scale
可以得到像素,这些像素适合于创建与原始像素数量相同的CGContext
。然后,在创建新的UIImage
时传递scale
,让它知道其点大小应该不同于CGImage
的像素大小。有可能它应该是1.0/scale
。就是这样!将高度和宽度的比例因子设置为2很重要,并将CG图像的比例设置为相同的因子。它在我的脑海中并没有完全转换,因为更大的比例因子使它更小,但更高的清晰度。比例因子是每个点有多少像素。在第一种情况下(将宽度和高度乘以比例),将从点转换为像素。创建新的UIImage
时,您告诉系统如何将CGImage
的大小(以像素为单位)转换为UIImage
的大小(以点为单位)。如果没有解释,向下投票和关闭请求根本没有帮助。
let coloredImage = UIImage(cgImage: cgImage, scale:scale, orientation:.up)