IOS-图片的四种加载方式
程序员文章站
2022-05-15 18:41:47
...
1 本地加载
1)直接加载
UIImage *image1 = [UIImage imageNamed:@"3.jpg"];```
###2)资源包加载
NSString *path1 = [[NSBundle mainBundle] pathForResource:@"3" ofType:@"jpg"];
UIImage *image2 = [UIImage imageWithContentsOfFile:path1];
##2 沙盒加载(可通过本地图片保存到沙盒也可通过网络保存到沙盒)
//保存到沙盒中
NSURL *url = [NSURL URLWithString:@"http://v1.qzone.cc/pic/201303/28/14/53/5153e8d54236f919.jpg!600x600.jpg"];
NSData *data = [NSData dataWithContentsOfURL:url];
UIImage *image3 = [UIImage imageWithData:data];
NSData *data1 = UIImageJPEGRepresentation(image1, 1);
NSString *path2 = [NSHomeDirectory() stringByAppendingString:@"/Documents/icon.jpg"];
[data1 writeToFile:path2 atomically:YES];
//从沙盒中读取图片
UIImage *image4 = [[UIImage alloc] initWithContentsOfFile:path2];
##3 网络加载
**(记得打开"App Transport Security Settings")**
NSURL *url1 = [NSURL URLWithString:@"http://v1.qzone.cc/pic/201303/28/14/53/5153e8d54236f919.jpg!600x600.jpg"];
NSData *data2 = [NSData dataWithContentsOfURL:url1];
UIImage *image = [UIImage imageWithData:data];
//compressionQuality图像的范围为0.0(最低品质)到1.0(最高品质)的压缩系数
data2 = UIImageJPEGRepresentation(image, 1);
image = [UIImage imageWithData:data2];```
4 相册加载 :UIImagePickerController
上一篇: 一些样式小效果