我有一个大尺寸的图像(2048 * 2048px),这个图像在iPhone屏幕上显示为320 * 320。我想这样做:
在我的应用程序中,用户可以打开大尺寸图像(例如2048 * 2048),图像在iPhone屏幕上显示为320 * 320,并且图像上有矩形,用户可以将矩形移动到iPhone屏幕上图像内的任意位置,例如矩形(100,100,300,200),然后我想按比例在矩形区域内剪辑原始大小的图像。
我尝试了很多方法,
UIImageView *originalImageView = [[UIImage View alloc] initWithImage:originalImage]];
CGRect rect = CGRectMake(100, 100, 300, 200);
UIImage *cropImage = [UIImage imageWithCGImage:CGImageCreateWithImageInRect([originalImageView.image CGImage], rect)];
但是我得到的裁剪图像只是300 * 200大小的图像,无法正确缩放。
这样做怎么样,它将保留原始图像质量
CGSize bounds = CGSizeMake(320,320) // Considering image is shown in 320*320
CGRect rect = CGRectMake(100, 100, 220, 200); //rectangle area to be cropped
float widthFactor = rect.size.width * (originalImage.size.width/bounds.size.width);
float heightFactor = rect.size.height * (originalImage.size.height/bounds.size.height);
float factorX = rect.origin.x * (originalImage.size.width/bounds.size.width);
float factorY = rect.origin.y * (originalImage.size.height/bounds.size.height);
CGRect factoredRect = CGRectMake(factorX,factorY,widthFactor,heightFactor);
UIImage *cropImage = [UIImage imageWithCGImage:CGImageCreateWithImageInRect([originalImage CGImage], factoredRect)];
最重要的是,如果您想裁剪imagePickerController返回的图像,那么这可以通过内置函数来完成,如下所示,
imagePickerController.allowsEditing = YES;
首先使用此方法调整大小为 320*320 的图像大小:
+(UIImage *)resizeImage:(UIImage *)image width:(float)width height:(float)height
{
CGSize newSize;
newSize.width = width;
newSize.height = height
UIGraphicsBeginImageContext(newSize);
[image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
}
现在在图像视图中设置调整大小的图像
UIImage *resizeImage = [YourControllerName resizeImage:originalImage width:320 height:320];
UIImageView *originalImageView = [[UIImage View alloc] initWithImage:resizeImage]];
您现在可以裁剪
CGRect rect = CGRectMake(100, 100, 300, 200);
UIImage *cropImage = [UIImage imageWithCGImage:CGImageCreateWithImageInRect([originalImageView.image CGImage], rect)];
为什么不计算比例因子(例如 originalImageWidth/smallImageWidth)?如果矩形(100,100,300,200)
在小图像中,则应以 (100*factor,100*factor,300*factor,200*factor)
大小裁剪 lage 图像。