根据任何视图的框架裁剪图像

Crop image according to frame of any View

我有一张图片,我想根据任何视图的框架裁剪它。例如;

我真的找不到解决办法。找了2天

BEFORE

AFTER

已编辑

感谢@Ajharul Islam 和@Bence Pattogato。两个答案都有效。

Swift @Ajharul Islam 解决方案的版本。

      func images(byCroppingImage image: UIImage?, to size: CGSize) -> UIImage? {
        // not equivalent to image.size (which depends on the imageOrientation)!
        let refWidth = (image?.cgImage?.width)!
        let refHeight = (image?.cgImage?.height)!


        let x = (Double(refWidth) - Double(size.width)) / 2
        let y = (Double(refHeight) - Double(size.height)) / 2



        let cropRect = CGRect(x: CGFloat(x), y: CGFloat(y), width: size.width, height: size.height)


        let imageRef = image?.cgImage!.cropping(to: cropRect) as! CGImage

        var cropped: UIImage? = nil
        if let imageRefs = image?.cgImage!.cropping(to: cropRect) {
            cropped = UIImage(cgImage: imageRefs, scale: 0.0, orientation: UIImage.Orientation.up)
        }


        return cropped
    }

让我说说我的错误以及我在尝试什么

我正在尝试拍照并根据任何视图的框架进行裁剪。我试图根据该主视图裁剪图片而不调整其大小。所以每次都是从错误的方式裁剪。

我调整了图片大小,现在我可以成功裁剪图片了。但是调整大小会降低图片的质量。所以现在我想找到最好的方法。

谢谢

您可以使用此代码裁剪图像:

   - (UIImage *)imageByCroppingImage:(UIImage *)image toSize:(CGSize)size
{
    // not equivalent to image.size (which depends on the imageOrientation)!
    double refWidth = CGImageGetWidth(image.CGImage);
    double refHeight = CGImageGetHeight(image.CGImage);

    double x = (refWidth - size.width) / 2.0;
    double y = (refHeight - size.height) / 2.0;

    CGRect cropRect = CGRectMake(x, y, size.height, size.width);
    CGImageRef imageRef = CGImageCreateWithImageInRect([image CGImage], cropRect);

    UIImage *cropped = [UIImage imageWithCGImage:imageRef scale:0.0 orientation:self.imageOrientation];
    CGImageRelease(imageRef);

    return cropped;
}

传递您的图像和视图的矩形,您将从中心获得裁剪图像

您正在寻找 CIAffineTransform or the CIPerspectiveCorrection。我不确定哪个更适合您的用例,但它们应该都适用。例如,您可以像这样使用 CIPerspectiveCorrection:

(CIImageToWorkWith).applyingFilter("CIPerspectiveCorrection", parameters: [
                            "inputTopLeft" : CIVector(cgPoint: topleft),
                            "inputTopRight" : CIVector(cgPoint: topright),
                            "inputBottomLeft" : CIVector(cgPoint: bottomleft),
                            "inputBottomRight" : CIVector(cgPoint: bottomright)
                            ])

编辑:您不想裁剪图片。裁剪就像从图像中裁剪出一些东西而不缩放它。

我认为实现它的最简单方法如下:

extension UIImage {
    func crop(to rect: CGRect) -> UIImage? {
        guard let imageRef = cgImage, let cropped = imageRef.cropping(to: rect) else {
            return nil
        }
        return UIImage(cgImage: cropped)
    }
}