ios – 如何裁减UIImage,而不会失去它的规模财产?

目标:裁减UI Image(以2.0的比例属性开始)

我执行以下代码

let croppedCGImage = originalUIImage.cgImage!.cropping(to: cropRect)
let croppedUIImage = UIImage(cgImage: croppedCGImage!)

这段代码工作,但是结果,croppedUllmage,具有不正确的scale属性1.0.

创建最终图像时,我已经尝试指定了缩放比例:

let croppedUIImage = UIImage(cgImage: croppedCGImage!,scale: 2.0,orientation: .up)

这产生正确的比例,但是它将尺寸尺寸减半地不正确.

我该怎么办?

(*注意:UIImage上的scale属性很重要,因为我稍后用受尺度属性影响的UIImagePNGRepresentation(_ image:UIImage)保存图像)

编辑:

我得到以下工作.不幸的是,它比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!
    }
}

相关文章

UITabBarController 是 iOS 中用于管理和显示选项卡界面的一...
UITableView的重用机制避免了频繁创建和销毁单元格的开销,使...
Objective-C中,类的实例变量(instance variables)和属性(...
从内存管理的角度来看,block可以作为方法的传入参数是因为b...
WKWebView 是 iOS 开发中用于显示网页内容的组件,它是在 iO...
OC中常用的多线程编程技术: 1. NSThread NSThread是Objecti...