目标:裁剪一个 UIImage
(以 scale
属性 2.0 开头)
我执行以下代码:
let croppedCGImage = originalUIImage.cgImage!.cropping(to: cropRect)
let croppedUIImage = UIImage(cgImage: croppedCGImage!)
此代码有效,但结果 croppedUIImage
, 有一个不正确的 scale
1.0 的属性。
我试过指定 scale
创建最终图像时:
let croppedUIImage = UIImage(cgImage: croppedCGImage!, scale: 2.0, orientation: .up)
这产生了正确的比例,但它削减了 size
尺寸错误地减半。
我应该在这里做什么?
(*注意:UIImage 上的 scale
属性很重要,因为我稍后用 UIImagePNGRepresentation(_ image: UIImage)
保存图像,它受 scale
属性影响)
编辑:
我得到以下工作。不幸的是,它比 CGImage
慢得多。裁剪功能。
extension UIImage {
func cropping(to rect: CGRect) -> UIImage {
UIGraphicsBeginImageContextWithOptions(rect.size, false, self.scale)
self.draw(in: CGRect(x: -rect.origin.x, y: -rect.origin.y, width: self.size.width, height: self.size.height))
let croppedImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
return croppedImage
}
}
最佳答案
试试这个:
extension UIImage {
func imageByCropToRect(rect:CGRect, scale:Bool) -> UIImage {
var rect = rect
var scaleFactor: CGFloat = 1.0
if scale {
scaleFactor = self.scale
rect.origin.x *= scaleFactor
rect.origin.y *= scaleFactor
rect.size.width *= scaleFactor
rect.size.height *= scaleFactor
}
var image: UIImage? = nil;
if rect.size.width > 0 && rect.size.height > 0 {
let imageRef = self.cgImage!.cropping(to: rect)
image = UIImage(cgImage: imageRef!, scale: scaleFactor, orientation: self.imageOrientation)
}
return image!
}
}
关于ios - 如何在不丢失其缩放属性的情况下裁剪 UIImage?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39655118/