ios - 如何在不丢失其缩放属性的情况下裁剪 UIImage?

标签 ios swift uiimage core-graphics cgimage

目标:裁剪一个 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/

相关文章:

ios - 使用 `.receive(on: DispatchQueue.main)` 时未接收到输入

ios - Facebook 和谷歌使用 Swift 登录

ios - 在 Swift 中对 UITabBarController 进行 segue 后如何摆脱 UINavigationController?

c# - 在 Xamarin Forms for iOS 的底部和编辑器上添加边框

ios - 在 swift ios 中滑动后,有没有办法在 uipageviewcontroller 中释放页面?

ios - 如何在一个类或 .swift 文件中编写一个方法并在整个代码中调用该方法?

uiviewcontroller - swift + Xcode 6 : What method is called when storyboard segue is performed

Swift UIButton BarButtonItem 中图像大小扭曲

ios - UIImage PNG 不透明度调整

iphone - 如何获取 UIImage 的地理坐标?