iOS本地加载图片的两种方式

2021-02-20  本文已影响0人  Queen_BJ

这两种方式有什么区别

imageNamed方法

1、图片可以存在项目中,也可以存在Assets中,都可以加载出来
2、适合中小型图片
3、有缓存

优点:当加载同样一个图标的时候,那么用imageNamed加载图像效率高,因为系统会把那个图标Cache到内存,每次需要这个图像的时候,只会把图片指针指向同一块内存。
缺点:虽然提高了运行速度,但是非常消耗内存,有些图片只需加载一次,不会在用了,消耗内存。

imageWithContentsOfFile方法

1、参数是路径,格式字符串
2、无缓存,根据路径查找
3、适合不常用图片和比较大的资源

优点:节省内存
缺点:消耗性能

总结: 一些小的icon可以存在Assets里面.用imageNamed加载. 一些比较大的,使用频率低的可以建立一个bundle存放图片,使用imageWithContentsOfFile加载.

拖入显示
存放在assert显示
 self.imgView.image = [UIImage imageNamed:@"showImg"];
 self.imgView.image = [UIImage imageNamed:@"showImg" inBundle:[NSBundle mainBundle] withConfiguration:nil];

拖入项目中显示
 self.imgView.image = [UIImage imageNamed:@"showImg"];
 self.imgView.image = [UIImage imageNamed:@"showImg" inBundle:[NSBundle mainBundle] withConfiguration:nil];

 NSString *path = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"showImg"];
    self.imgView.image = [UIImage imageWithContentsOfFile:path];

必须是@2x @3x具体类型,showImg不显示
 NSString *path = [[NSBundle mainBundle]pathForResource:@"showImg@2x.png" ofType:nil];
    self.imgView.image = [UIImage imageWithContentsOfFile:path];

assert中不显示方法

 NSString *path = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"showImg"];
    self.imgView.image = [UIImage imageWithContentsOfFile:path];

showImg.png 和 showImg@2x.png都不显示
 NSString *path = [[NSBundle mainBundle]pathForResource:@"showImg.png" ofType:nil];
    self.imgView.image = [UIImage imageWithContentsOfFile:path];
上一篇 下一篇

猜你喜欢

热点阅读