【问题标题】:How to crop image view given a rect如何裁剪给定矩形的图像视图
【发布时间】:2019-03-14 21:07:59
【问题描述】:

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

【问题讨论】:

    标签: ios objective-c crop


    【解决方案1】:

    您可以使用下面的代码块来做到这一点。

    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
    }
    

    【讨论】:

    • 对我不起作用。 rect 的值应该是什么?
    【解决方案2】:
    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!;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-08-13
      • 1970-01-01
      • 2021-06-21
      • 2014-12-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多