CGImageCreateWithImageInRect

时间:2018-07-12 19:36:24

标签: objective-c crop cgimageref

我正在尝试创建一个简单的裁剪应用程序。我有一个覆盖在UIImage上的视图,我想只从覆盖该视图的UIImage部分中裁剪出一个新图像。我使用了代码

CGRect cropRect = _cropView.frame;
UIImage *cropImage = [UIImage imageWithData:imageData];
CGImageRef cropped = CGImageCreateWithImageInRect([cropImage CGImage], cropRect);
UIImage *croppedImage = [UIImage imageWithCGImage:cropped];
self.imageView.image = croppedImage;

但是它导致了意外的图像,看起来非常放大,而不是我想要的。如何从视图后面的图像中裁剪新图像?

2 个答案:

答案 0 :(得分:0)

CGImage处理像素,而不是“点”(UIKit的抽象测量单位)。裁剪视图的contentScaleFactor大于1时,其像素尺寸将大于其点尺寸。因此,要获得与像素对应的裁剪矩形,您需要将视图frame的所有坐标和尺寸乘以其contentScaleFactor

CGRect cropRect = _cropView.frame;
cropRect.origin.x *= _cropView.contentScaleFactor;
cropRect.origin.y *= _cropView.contentScaleFactor;
cropRect.size.width *= _cropView.contentScaleFactor;
cropRect.size.height *= _cropView.contentScaleFactor;

答案 1 :(得分:0)

这可能对您有帮助

// Create new image context
CGSize size = _cropView.frame.size;

UIGraphicsBeginImageContextWithOptions(size, NO, 0.0);

// Create rect for image
CGRect rect = _cropView.frame;

// Draw the image into the rect
[existingImage drawInRect:rect];

// Saving the image, ending image context
UIImage * newImage = UIGraphicsGetImageFromCurrentImageContext();

UIGraphicsEndImageContext();