简体   繁体   English

如何裁剪给定的图像视图

[英]How to crop image view given a rect

I want to display the crop view on uiimagepickercontrollers overlayView, and then crop the image with respect to the overlayImage rect. 我想在uiimagepickercontrollers overlayView上显示裁剪视图,然后相对于overlayImage rect裁剪图像。 How can I calculate crop image given the rect of overlayView? 给定overlayView的矩形,如何计算裁剪图像?

private func CropImage( image:UIImage , cropRect:CGRect) -> UIImage
{
    UIGraphicsBeginImageContextWithOptions(cropRect.size, false, 0);
    let context = UIGraphicsGetCurrentContext();

    context?.translateBy(x: 0.0, y: image.size.height);
    context?.scaleBy(x: 1.0, y: -1.0);
    context?.draw(image.cgImage!, in: CGRect(x:0, y:0, width:image.size.width, height:image.size.height), byTiling: false);
    context?.clip(to: [cropRect]);

    let croppedImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return croppedImage!;
}

You can do it by using below chunk of code. 您可以使用下面的代码块来实现。

let imageRef:CGImage = uncroppedImage.cgImage!.cropping(to: bounds)!
let croppedImage:UIImage = UIImage(cgImage: imageRef)

Here you can pass your rect according to your requirement. 在这里,您可以根据自己的要求通过您的矩形。

Also you can do it as as per apple suggestion. 您也可以按照苹果的建议进行操作。

Please find Official documentatation. 请找到官方文档。

func cropImage(_ inputImage: UIImage, toRect cropRect: CGRect, viewWidth: CGFloat, viewHeight: CGFloat) -> UIImage? 
{    
    let imageViewScale = max(inputImage.size.width / viewWidth,
                             inputImage.size.height / viewHeight)

    // Scale cropRect to handle images larger than shown-on-screen size
    let cropZone = CGRect(x:cropRect.origin.x * imageViewScale,
                          y:cropRect.origin.y * imageViewScale,
                          width:cropRect.size.width * imageViewScale,
                          height:cropRect.size.height * imageViewScale)

    // Perform cropping in Core Graphics
    guard let cutImageRef: CGImage = inputImage.cgImage?.cropping(to:cropZone)
    else {
        return nil
    }

    // Return image to UIImage
    let croppedImage: UIImage = UIImage(cgImage: cutImageRef)
    return croppedImage
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM