回顧一個經(jīng)典面試題
加載網(wǎng)絡(luò)圖片拓颓,或者從相冊讀取圖片的時候,如果ImageView的本身就是固定的200x200么伯,加載800x800的圖片會有什么問題叶撒?
答案:載入800x800的圖片用到200x200的控件上是很浪費內(nèi)存。需要消耗的內(nèi)存大小800x800x4bit贪嫂。(解決方案:在使用前把圖片調(diào)整到需要的大兴伦)
方法如下:
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官方文檔的解釋:一個支持創(chuàng)建核心圖像的渲染器。
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兆左右的大圖速度確實提升很多力崇。