缩略图在使用图像的任何应用程序中都发挥着重要的作用。我们常需要调整图像的大小以将其放入一个较小的空间。
当然,你可以装载一个完全填充有原图的 UIImangeView 并调整其框架的大小,不过将图像重新绘制为占用较小字节
的图像可节省大量内存。重绘缩略图可使用以下3种方法,分别是调整、居中、填充方式。
1、保持图像比例不变的同时调整其大小。需要根据图像的长宽比在其四周留出一些额外区域,用透明像素为图像消关。
2、抽取部分图像来匹配可用空间。并裁剪掉落在像素区外的任何元素。
3、通过匹配可用空间的长度和宽度来填充图像。每个像素都被使用,但是图像将水平或垂直裁剪。
源代码:
//计算适合的大小。并保留其原始图片大小
+ (CGSize) fitSize: (CGSize)thisSize inSize: (CGSize) aSize
{
CGFloat scale;
CGSize newsize = thisSize;
if (newsize.height && (newsize.height > aSize.height))
{
scale = aSize.height / newsize.height;
newsize.width *= scale;
newsize.height *= scale;
}
if (newsize.width && (newsize.width >= aSize.width))
{
scale = aSize.width / newsize.width;
newsize.width *= scale;
newsize.height *= scale;
}
return newsize;
}
//返回调整的缩略图
+ (UIImage *) image: (UIImage *) image fitInSize: (CGSize) viewsize
{
// calculate the fitted size
CGSize size = [ImageHelper fitSize:image.size inSize:viewsize];
UIGraphicsBeginImageContext(viewsize);
float dwidth = (viewsize.width - size.width) / 2.0f;
float dheight = (viewsize.height - size.height) / 2.0f;
CGRect rect = CGRectMake(dwidth, dheight, size.width, size.height);
[image drawInRect:rect];
UIImage *newimg = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newimg;
}
//返回居中的缩略图
+ (UIImage *) image: (UIImage *) image centerInSize: (CGSize) viewsize
{
CGSize size = image.size;
UIGraphicsBeginImageContext(viewsize);
float dwidth = (viewsize.width - size.width) / 2.0f;
float dheight = (viewsize.height - size.height) / 2.0f;
CGRect rect = CGRectMake(dwidth, dheight, size.width, size.height);
[image drawInRect:rect];
UIImage *newimg = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newimg;
}
//返回填充的缩略图
+ (UIImage *) image: (UIImage *) image fillSize: (CGSize) viewsize
{
CGSize size = image.size;
CGFloat scalex = viewsize.width / size.width;
CGFloat scaley = viewsize.height / size.height;
CGFloat scale = MAX(scalex, scaley);
UIGraphicsBeginImageContext(viewsize);
CGFloat width = size.width * scale;
CGFloat height = size.height * scale;
float dwidth = ((viewsize.width - width) / 2.0f);
float dheight = ((viewsize.height - height) / 2.0f);
CGRect rect = CGRectMake(dwidth, dheight, size.width * scale, size.height * scale);
[image drawInRect:rect];
UIImage *newimg = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newimg;
}