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



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

我真的找不到解决方案。我已经搜索了 2 天。

以前

已编辑

感谢@Ajharul伊斯兰教和@Bence帕托加托。这两个答案都有效。

@Ajharul伊斯兰教解决方案的快速版本。

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
}

让我说出我的错误以及我试图做什么

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

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

谢谢

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

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)
}
}

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

- (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或CIPerspectiveCorrection。我不确定哪个更适合您的用例,但它们应该同时工作。例如,你可以像这样使用 CIPerspectiveCorrection:

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

编辑:您不想裁剪图像。裁剪就像从图像中剪切某些内容而不缩放它。

最新更新