回顾一个经典面试题
加载网络图片,或者从相册读取图片的时候,如果ImageView的本身就是固定的200x200,加载800x800的图片会有什么问题?
答案:载入800x800的图片用到200x200的控件上是很浪费内存。需要消耗的内存大小800x800x4bit。(解决方案:在使用前把图片调整到需要的大小)
方法如下:
func imageWithImageScaledToSize(image:UIImage,newSize:CGSize) -> UIImage {
UIGraphicsBeginImageContext(newSize)
image.draw(in: CGRect.init(x: 0, y: 0, width: newSize.width, height: newSize.height))
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage!
}
func imageWithImageResizerFactor(image:UIImage,scale:CGFloat) -> UIImage {
let originalSize = image.size
let newSize = CGSize.init(width: originalSize.width*scale, height: originalSize.height*scale)
UIGraphicsBeginImageContext(newSize)
image.draw(in: CGRect.init(x: 0, y: 0, width: newSize.width, height: newSize.height))
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage!
}
iOS10新增UIGraphicsImageRenderer来代替UIGraphicsBeginImageContext
UIGraphicsImageRenderer官方文档的解释:一个支持创建核心图像的渲染器。
ggImageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 300, 400, 300)];
[self.view addSubview:ggImageView];
NSURL *imgUrl = [[NSBundle mainBundle] URLForResource:@"DSC_0645" withExtension:@"jpeg"];
UIImage *ggImage = [self resiImage:imgUrl size:ggImageView.bounds.size];
ggImageView.image = ggImage;
//常用的加载大图方法
// ggImageView.image = [UIImage imageWithContentsOfFile:imgUrl.path];
//绘制UIImage
- (UIImage*)resiImage:(NSURL*)url size:(CGSize)size{
UIImage *testIm = [UIImage imageWithContentsOfFile:url.path];
UIGraphicsImageRenderer *re = [[UIGraphicsImageRenderer alloc]initWithSize:size];
return [re imageWithActions:^(UIGraphicsImageRendererContext * _Nonnull rendererContext) {
[testIm drawInRect:CGRectMake(0, 0, size.width, size.height)];
}];
}
加载10兆左右的大图速度确实提升很多。
网友评论