【问题标题】:Cropping big size image and set in imageview's frame裁剪大尺寸图像并设置在 imageview 的框架中
【发布时间】:2026-02-23 04:50:01
【问题描述】:

这个问题问了很多时间,但我的问题完全不同。

我正在从 Json(网络服务)获取图像。就像“http://address/upload/book_icon/4353988696.jpg”。

我需要以 85 * 130 尺寸显示图像以适合 imageview。但大多数图像的尺寸要大得多。

例如:如果图像的大小为 1000*650,那么我如何将此图像设置为 85*130 而无需下载。

为了更快地显示图像,我正在使用“SDWebImageManagerDelegate”,但需要快速裁剪图​​像并在 imageview 中显示而不下载它。

到目前为止我做到了......

NSString *stringURL = [NSString stringWithFormat:@"%@",[imageURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
        UIImageView *imgView = [[UIImageView alloc] initWithFrame:CGRectMake(0,0, 85,130)];
        [imgView setBackgroundColor:[UIColor whiteColor]];
        imgView.tag = i;

但由于裁剪图像而没有使用下面的行来获取图像...

        [imgView setImageWithURL:[NSURL URLWithString:stringURL] placeholderImage:[UIImage imageNamed:@"no_image.png"]];  

并用它来获取图像...

NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:stringURL]];
        UIImage *image123temp = [UIImage imageWithData:data];
UIImage *objimgtemp = [self imageCrop:image123temp];

        imgView.image = objimgtemp; 

并使用此方法裁剪图像

-(UIImage*)imageCrop:(UIImage*)original
{
UIImage *ret = nil;

// This calculates the crop area.

float originalWidth  = original.size.width;
float originalHeight = original.size.height;

float edge = fminf(originalWidth, originalHeight);

float posX = (originalWidth   - edge) / 2.0f;
float posY = (originalHeight  - edge) / 2.0f;


CGRect cropSquare = CGRectMake(posX, posY,
                               edge, edge);


// This performs the image cropping.

CGImageRef imageRef = CGImageCreateWithImageInRect([original CGImage], cropSquare);

ret = [UIImage imageWithCGImage:imageRef
                          scale:original.scale
                    orientation:original.imageOrientation];

CGImageRelease(imageRef);

NSLog(@"ret.......... %f == %f",ret.size.width,ret.size.height);

return ret;
}

如何快速获得裁剪图像?

任何链接、教程、建议、代码,都会有很大帮助...

【问题讨论】:

  • 您的意思是从服务器获取缩略图?这是通常所做的,但服务器必须支持缩略图。我看不出你自己会如何做到这一点。如果你只能得到一个完整的图像文件,你需要下载一个完整的文件,在内存中解压缩,然后你才能裁剪、呈现或用它做任何事情......

标签: ios uiimageview uiimage cgrect


【解决方案1】:

位于远程 URL 的图像始终按原样下载。在远程服务器上创建图像缩略图版本或在客户端请求时自动缩放/自动裁剪图像的任何内容 是服务器端进程而不是客户端进程。

现在你可以做的是创建一个简单的服务器端 webrequest(用 PHP 或其他语言),它返回一个 裁剪后的图像当然会更小。 然后你会在客户端做这样的事情:

NSString *stringURL = [NSString stringWithFormat:@"http://www.example.com/getCroppedImage?width=%f&height=%f&imagename=%@", width, height, someImageName];
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:stringURL]];

【讨论】: