2

我有一个大尺寸的图像(2048*2048px),这个图像在 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 大小的图像,不能正确缩放。

4

3 回答 3

1

首先使用此方法调整大小为 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)];
于 2012-06-27T02:50:54.633 回答
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;
于 2012-06-27T02:51:20.047 回答
0

为什么不计算比例因子(例如 originalImageWidth/smallImageWidth)?如果矩形(100,100,300,200)在您的小图像中,您应该将拉格图像裁剪为 size (100*factor,100*factor,300*factor,200*factor)

于 2012-06-27T01:59:32.133 回答