如何裁剪给定的图像视图

时间:2018-10-10 03:06:07

标签: ios objective-c crop

我想在uiimagepickercontrollers overlayView上显示裁剪视图,然后相对于overlayImage rect裁剪图像。给定overlayView的矩形,如何计算裁剪图像?

2 个答案:

答案 0 :(得分:0)

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!;
}

答案 1 :(得分:0)

您可以通过使用下面的代码块来实现。

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

在这里您可以根据自己的要求通过考试。

您也可以按照苹果的建议进行操作。

请找到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
}