我们获取的网络图片, 设置到按钮活tabbar上往往都很模糊,如何使网络下载的图片按照2x或3x显示呢?(比如60*60的原始图片, 显示为30*30的大小,实现2倍率显示)
#pragma mark - 无损缩小图片:按比例
-(UIImage *)scaleImage:(UIImage *)image scale:(CGFloat)scale{
NSData *imageData = UIImagePNGRepresentation(image);
UIImage *imageNew = [UIImage imageWithData:imageData scale:scale];
return imageNew;
}
SDWebImageManager *manager = [SDWebImageManager sharedManager];
NSURL *url = [NSURL URLWithString:iconUrl]
[manager downloadImageWithURL:url options:SDWebImageRetryFailed progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) {
if (image) {
image = [self scaleImage:image scale:2.0];
shouyeVC.tabBarItem.selectedImage = [image imageWithRenderingMode:UIImageRenderingModeAutomatic];
}
}];
还有一个比较好用的方法, 就是将得到的网络图片image进行尺寸压缩到指定大小, 而图片不失真.
/*
*return 新生成的图片
* targetSize 新生成图片的尺寸(你想得到的尺寸)
* image原始图片
*/
- (UIImage *)imageByScalingToSize:(CGSize)targetSize ForImage:(UIImage *)image{
//用作3倍率缩放, 保证图片不失真
targetSize = CGSizeMake(targetSize.width*3, targetSize.height*3);
UIImage *sourceImage = image;
UIImage *newImage = nil;
CGSize imageSize = sourceImage.size;
CGFloat width = imageSize.width;
CGFloat height = imageSize.height;
CGFloat targetWidth = targetSize.width;
CGFloat targetHeight = targetSize.height;
CGFloat scaleFactor = 0.0;
CGFloat scaledWidth = targetWidth;
CGFloat scaledHeight = targetHeight;
CGPoint thumbnailPoint = CGPointMake(0.0,0.0);
if (CGSizeEqualToSize(imageSize, targetSize) == NO) {
CGFloat widthFactor = targetWidth / width;
CGFloat heightFactor = targetHeight / height;
if (widthFactor < heightFactor)
scaleFactor = widthFactor;
else
scaleFactor = heightFactor;
scaledWidth = width * scaleFactor;
scaledHeight = height * scaleFactor;
// center the image
if (widthFactor < heightFactor) {
thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5;
} else if (widthFactor > heightFactor) {
thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5;
}
}
// this is actually the interesting part:
UIGraphicsBeginImageContext(targetSize);
CGRect thumbnailRect = CGRectZero;
thumbnailRect.origin = thumbnailPoint;
thumbnailRect.size.width = scaledWidth;
thumbnailRect.size.height = scaledHeight;
[sourceImage drawInRect:thumbnailRect];
newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
if(newImage == nil)
NSLog(@"could not scale image");
UIImage *image3Scale = [[UIImage alloc] initWithData:UIImagePNGRepresentation(newImage) scale:3.0];
return image3Scale;
}
网友评论