已知CGRect对UIImage对象进行裁剪使用CGImageCreateWithImageInRect裁剪出的图片很模糊
CGImageCreateWithImageInRect方法裁剪出的图片模糊可能是因为裁剪区域的尺寸与图片的分辨率不匹配导致的。可以尝试使用UIGraphicsBeginImageContextWithOptions方法创建一个新的图形上下文,并设置其分辨率为当前屏幕的缩放比例,然后将原始UIImage对象绘制到新的图形上下文中,再通过CGRectApplyAffineTransform方法将CGRect对象按照缩放比例进行变换,最后使用CGImageCreateWithImageInRect方法对新的图形上下文进行裁剪,可以得到更清晰的裁剪结果。
下面是一个示例代码:
func croppedImage(from rect: CGRect, image: UIImage) -> UIImage? {
let scale = UIScreen.main.scale // 获取屏幕缩放比例
let scaledRect = CGRect(x: rect.origin.x * scale, y: rect.origin.y * scale, width: rect.size.width * scale, height: rect.size.height * scale) // 将裁剪区域按照缩放比例进行变换
UIGraphicsBeginImageContextWithOptions(image.size, false, scale) // 创建一个新的图形上下文
image.draw(at: CGPoint.zero) // 将原始图片绘制到新的图形上下文中
let croppedImage = UIGraphicsGetImageFromCurrentImageContext() // 获取绘制后的图片
UIGraphicsEndImageContext() // 关闭图形上下文
if let croppedCGImage = croppedImage?.cgImage?.cropping(to: scaledRect) { // 对绘制后的图片进行裁剪
return UIImage(cgImage: croppedCGImage, scale: scale, orientation: image.imageOrientation)
}
return nil
}
使用示例:
let originalImage = UIImage(named: "originalImage")
let croppedRect = CGRect(x: 10, y: 10, width: 100, height: 100)
let croppedImage = croppedImage(from: croppedRect, image: originalImage)
这样可以得到一个清晰的裁剪结果。
原文地址: https://www.cveoy.top/t/topic/jesv 著作权归作者所有。请勿转载和采集!