UIImage 载入图像
【摘要】 用UIImage载入图像的方法非常多。最经常使用的是几种: 一、使用 imageNamed 函数载入[UIImage imageNamed:ImageName:@"imageDemo"];代码示例如下:- (void)viewDidLoad { [super viewDidLoad]; //创建UIImage对象:指定图片为1.jpg UIImage *image = [U...
用UIImage
载入图像的方法非常多。最经常使用的是几种:
一、使用 imageNamed 函数载入
[UIImage imageNamed:ImageName:@"imageDemo"];
代码示例如下:
- (void)viewDidLoad {
[super viewDidLoad];
//创建UIImage对象:指定图片为1.jpg
UIImage *image = [UIImage imageNamed:@"1.jpg"];
//创建UIImageView对象,指定image对象为image
UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
//指定ImageView容器的位置及长宽
imageView.frame = CGRectMake(0, 0, image.size.width, image.size.height);
//指定图片以屏幕中心点放置
imageView.center = CGPointMake(self.view.frame.size.width*0.5, self.view.frame.size.height*0.5);
/*
几种UIImage的内容模式:
UIViewContentModeScaleToFill, //自动适应长宽(图片会变形)
UIViewContentModeScaleAspectFit, //自动适应宽度(如果图片过大,会被缩放)
UIViewContentModeScaleAspectFill, //自动填充(如果图片过大,只会显示一部分)
UIViewContentModeRedraw, //图片重绘
UIViewContentModeCenter, //图片以中心点放置
UIViewContentModeTop, //图片以顶部放置
UIViewContentModeBottom, //图片以底部放置
UIViewContentModeLeft, //图片以左边中心点放置
UIViewContentModeRight, //图片以右边边中心点放置
UIViewContentModeTopLeft, //图片以左上角放置
UIViewContentModeTopRight, //图片以右上角放置
UIViewContentModeBottomLeft, //图片以左下角放置
UIViewContentModeBottomRight, //图片以右下角放置
*/
imageView.contentMode = UIViewContentModeScaleToFill;
[self.view addSubview:imageView];
}
二、通过 NSData 方式载入
NSString *filePath = [[NSBundle mainBundle] pathForResource:fileName ofType:extension];
NSData *image = [NSData dataWithContentsOfFile:filePath];
[UIImage imageWithData:image];
三、使用 imageWithContentsOfFile 函数载入
通过NSBundle
对象的mainBundle
方法创建NSBundle
对象后调用pathForResource
方法获取图片路径。然后通过UIimage
的imageWithContentsOfFile
类方法创建图片对象。
NSString *path = [[NSBundle mainBundle] pathForResource:@”shq5785” ofType:@”png”];
myImage = [UIImage imageWithContentsOfFile:path];
注意⚠️:
-
应用
imageNamed
函数方式载入时。系统会把图像Cache
到内存。假设图像比較大。或者图像比較多。用这样的方式会消耗非常大的内存。可是利用imageNamed
载入图像也有自己的优势。对于同一个图像系统仅仅会把它Cache
到内存一次,这对于图像的反复利用是非常有优势的。 -
利用
NSData
或imageWithContentsOfFile
方式载入时。仅载入图片,图像数据不会缓存。因此对于较大的图片以及使用情况较少时,那就能够用该方法,减少内存消耗。 -
通过
imageNamed
类方法加载的图片,通常放置在Assets.xcassets
中且也能加载ipa包路径下的图片资源。
通过imageWithContentsOfFile
类方法加载的图片,只能获取ipa包路径下的图片资源。
四、拓展阅读
【版权声明】本文为华为云社区用户原创内容,未经允许不得转载,如需转载请自行联系原作者进行授权。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
作者其他文章
评论(0)