如何快速裁剪图​​像

Posted

技术标签:

【中文标题】如何快速裁剪图​​像【英文标题】:How to crop an image in swift 【发布时间】:2018-08-14 09:09:30 【问题描述】:

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

【问题讨论】:

【参考方案1】:
extension UIImage   
    // Crops an input image (self) to a specified rect
    func cropToRect(rect: CGRect!) -> UIImage? 
        // Correct rect size based on the device screen scale
        let scaledRect = CGRectMake(rect.origin.x * self.scale, rect.origin.y * self.scale, rect.size.width * self.scale, rect.size.height * self.scale);
        // New CGImage reference based on the input image (self) and the specified rect
        let imageRef = CGImageCreateWithImageInRect(self.CGImage, scaledRect);
        // Gets an UIImage from the CGImage
        let result = UIImage(CGImage: imageRef, scale: self.scale, orientation: self.imageOrientation)
        // Returns the final image, or NULL on error
        return result;
        


// Crops an image to 100x100 pixels, 150px from left and 200px from top
let exampleImage = UIImage(named: "yourImageFile")
let croppedImage = exampleImage?.cropToRect(CGRectMake(150.0, 200.0, 100.0, 100.0))
if croppedImage != nil 
    // Your image was cropped
 else 
    // Something went wrong

【讨论】:

【参考方案2】:

将Apple's developer documentation 与Pranavan Sp 已弃用的答案结合起来,以跳过花里胡哨,你会得到:

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
    

【讨论】:

【参考方案3】:

您好,您可以使用此代码调整图像大小。

【讨论】:

以上是关于如何快速裁剪图​​像的主要内容,如果未能解决你的问题,请参考以下文章

FL水果如何裁剪歌曲?

如何让图像在中心裁剪

如何从 jpeg 的顶部和底部裁剪 45px

无法使用 CGImageCreateWithImageInRect 快速裁剪触摸位置

如何在裁剪前不修剪的情况下以小形式裁剪大图像?

通过裁剪获取新图像