iOS开发之UI篇(2)—— UIImageView

来源:互联网 发布:洛奇英雄传优化 编辑:程序博客网 时间:2024/06/03 23:44

版本

Xcode 9.1

@interface UIImageView : UIView

UIImageView继承自UIView,因此拥有view的属性以及可以使用view的方法。
在创建UIImageView的image对象的时候,可以有几种不同方法,主要差别体现在内存分配上:

1. 使用imageNamed

  • 加载成功后系统会把图像缓存到内存,下次再读取时直接从缓存中获取,因此访问效率要比较高。
  • 通常用于加载bundle中的小图片资源,一般应用于TableView中或者背景图片等。

2. 使用imageWithContentsOfFile

  • 仅仅加载图片而不在内存中缓存下来,每次获取时都会根据路径重新去加载。
  • 因为这是类方法加载的图片对象,会被放到自动释放池中,使用完后会被销毁回收内存,因此不会造成太多内存消耗
  • 当图片比较大且需要频繁使用时,一般使用该方法

3. 使用initWithContentsOfFile

  • 仅仅加载图片而不在内存中缓存下来,每次获取时都会根据路径重新去加载。
  • 当图片资源比较大,或者图片资源只使用一次就不再使用了,那么使用此种方式是最佳方式

4. 使用imageWithData

  • 图像会被系统以数据方式加载到程序。
  • 当不需要重用该图像,或者需要将图像以数据方式存储到数据库,又或者通过网络下载一个很大的图像时,使用该方法。

示例

    /* ----- 几种加载UIImage方式 ----- */    // 1.使用imageNamed    UIImage *image1 = [UIImage imageNamed:@"1.jpg"];    // 2.使用imageWithContentsOfFile    NSString *path = [[NSBundle mainBundle] pathForResource:@"1" ofType:@"jpg"];    UIImage *image2 = [UIImage imageWithContentsOfFile:path];    // 3.使用initWithContentsOfFile    UIImage *image3 = [[UIImage alloc] initWithContentsOfFile:path];    // 4.使用imageWithData    NSData *imageData = [NSData dataWithContentsOfFile:path];    UIImage *image4 = [UIImage imageWithData:imageData];    /* ----- 设置UIImageView属性 ----- */    // 在viewDidLoad里不要用self.view.frame,因为view还没有layout完成    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height)];    // 指定imageView的image对象    imageView.image = image1;    // 设置图片内容的布局方式    imageView.contentMode = UIViewContentModeScaleAspectFit;    // 设置imageView的背景    imageView.backgroundColor = [UIColor whiteColor];    // 设置imageView透明度    imageView.alpha = 1.0;    // 添加viewDidLoad到self.view    [self.view addSubview:imageView];    /* ----- 加载动态图 ----- */    NSString *path1 = [[NSBundle mainBundle] pathForResource:@"1" ofType:@"jpg"];    NSString *path2 = [[NSBundle mainBundle] pathForResource:@"2" ofType:@"jpg"];    NSString *path3 = [[NSBundle mainBundle] pathForResource:@"3" ofType:@"jpg"];    imageView.animationImages = @[[UIImage imageWithContentsOfFile:path1],[UIImage imageWithContentsOfFile:path2],[UIImage imageWithContentsOfFile:path3]];    imageView.animationDuration = 5.0f;     // 设置循环一次的时间    imageView.animationRepeatCount = 0;     // 设置循环次数(0为无线循环)    [imageView startAnimating];             // 开始动画//    [imageView stopAnimating];              // 停止动画


效果图

阅读全文
0 0