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

本文介绍了UIImageView的使用方法,包括不同图片加载方式的特点及应用场景,并演示如何设置UIImageView的属性以实现图片显示,还展示了如何加载动态图。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

版本

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];              // 停止动画


效果图

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值