如何快速裁剪图​​像 [英] How to crop an image in swift

查看:59
本文介绍了如何快速裁剪图​​像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从相机中裁剪图像.相机预览中应该有一个矩形边框,结果将是裁剪后的图像,如下例所示:

I want to crop an image from camera. There should be a rectangle border in the camera preview and the result will be the cropped image, like this example:

推荐答案

组合苹果的开发人员文档,其中 Pranavan Sp 弃用了答案,您将得到:/p>

Combining Apple's developer documentation with the deprecated answer by Pranavan Sp to skip the bells and whistles, you would get:

extension UIImage {

    func cropToRect(rect: CGRect!) -> UIImage? {

        let scaledRect = CGRect(x: rect.origin.x * self.scale, y: rect.origin.y * self.scale, width: rect.size.width * self.scale, height: rect.size.height * self.scale);


        guard let imageRef: CGImage = self.cgImage?.cropping(to:scaledRect)
        else {
            return nil
        }

        let croppedImage: UIImage = UIImage(cgImage: imageRef, scale: self.scale, orientation: self.imageOrientation)
        return croppedImage
    }
}

这篇关于如何快速裁剪图​​像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆