我有一个大尺寸的图像(2048 * 2048像素),此图像在iPhone屏幕上显示为320 * 320。我想这样做:
在我的APP中,用户可以打开大尺寸图像(例如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)];
但是我得到的cropImage只有300 * 200大小的图像,不能正确缩放。
答案 0 :(得分:1)
如何做到这一点,它将保留原始图像质量
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;
答案 1 :(得分:0)
为什么不计算比例因子(例如originalImageWidth / smallImageWidth)?
如果小图片中的矩形为(100,100,300,200)
,则应剪切大小为(100*factor,100*factor,300*factor,200*factor)
的图片。
答案 2 :(得分:0)
首先使用此方法调整大小为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();
}
现在在imageView中设置调整大小的图像
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)];