好多商城类的项目都有很多图片展示,这样会导致APP内存使用很高,因而我们的app使用起来感觉不流畅很卡,所以在我们上传图片之前最好是对图片做一下处理.使用系统的这两个方法并不能做到更好的优化(UIImagePNGRepresentation(image)),UIImageJPEGRepresentation(image,0.5)
以下最简单的方法是重绘图片:
oc代码:
```
//重新绘制图片,做到缩放功能
+(UIImage*)drawImage:(UIImage*)image width:(CGFloat)width {
CGFloatheight = (image.size.height/ image.size.width) * width;
CGSizesize =CGSizeMake(width, height);
UIGraphicsBeginImageContext(size);
[imagedrawInRect:CGRectMake(0,0, size.width, size.height)];
UIImage*newImage =UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
returnnewImage;
}
```
swift代码:
```
//重新绘制图片,做到缩放功能
classfuncdrawImage(image :UIImage, width :CGFloat) ->UIImage? {
letheight = (image.size.height/ image.size.width) * width
letsize =CGSize(width: width, height: height)
UIGraphicsBeginImageContext(size)
image.draw(in:CGRect(x:0, y:0, width: size.width, height: size.height))
letnewImage =UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
returnnewImage ??nil
}
```