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

前端之家收集整理的这篇文章主要介绍了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!
    }
}
原文链接:https://www.f2er.com/iOS/337390.html

猜你在找的iOS相关文章