1.簡單認(rèn)識
UIImageView對象提供了一個基于視圖的容器來展示一張或者一系列圖像,同時也支持以動畫的方式來呈現(xiàn)一組圖像(可以指定播放間隔和頻率)。簡單的說,UIImageView就是UIImage對象的承載者,當(dāng)需要將UIImage呈現(xiàn)在UIView上時就需要UIImageView。二者的關(guān)系就像UILabel和NSString之間的關(guān)系。
2.屬性~方法
UIImageView的常用屬性和方法:
- contentMode屬性:圖片的填充模式。(繼承自UIView)
- clipsToBounds屬性:修剪超出邊界的部分。(繼承自UIView)
- animationImages屬性:裝在用于動畫的圖像的數(shù)組。
- animationDuration屬性:動畫播放的持續(xù)時間。
- animationRepeatCount屬性:動畫的重復(fù)次數(shù),0表示循環(huán)播放。
- -startAnimating方法:開始播放動畫。
- -stopAnimating方法:停止播放動畫。
- -isAnimating方法:返回BOOL值表示動畫是否正在播放中。
2.1 三種contentMode屬性

3.用UIImageView來實現(xiàn)一個動畫的demo如下:
#import "ViewController.h"
@interface ViewController () {
NSTimer *timer;
}
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// 用一個數(shù)組來裝構(gòu)成動畫的所有圖片
NSMutableArray *imageArray = [NSMutableArray array];
for (int i = 0; i < 6; i++) {
[imageArray addObject:[UIImage imageNamed:[NSString stringWithFormat:@"runner%d.jpg", i]]];
}
// 創(chuàng)建UIImageView對象并指定相關(guān)的動畫圖片
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 150, 75, 100)];
imageView.animationImages = [imageArray copy];
// 設(shè)置圖片切換的時間間隔
imageView.animationDuration = 0.5;
imageView.tag = 101;
// imageView.animationRepeatCount = 10;
// 開始動畫
[imageView startAnimating];
[self.view addSubview:imageView];
// 啟動一個計時器讓UIImageView向右移動
timer = [NSTimer scheduledTimerWithTimeInterval:0.01 target:self selector:@selector(runAhead) userInfo:nil repeats:YES];
}
// 修改UIImageView的x坐標(biāo)使其向右移動并在到達(dá)邊界時返回
- (void) runAhead {
UIImageView *currentView = (id)[self.view viewWithTag:101];
CGRect rect = currentView.frame;
rect.origin.x += 1;
if(rect.origin.x > self.view.bounds.size.width) {
rect.origin.x = -75;
}
currentView.frame = rect;
}
@end
效果大致如下:


4.UIImage簡介

// 此種方式會對加載的圖片進(jìn)行單例處理,不適合動態(tài)加載大量圖片,因為單例對象會一直存在于內(nèi)存中
UIImage *image1 = [UIImage imageNamed:@"abc"];
NSString * strPath = [[NSBundle mainBundle] pathForResource:@"abc" ofType:@"png"];
// 此方式適合本地動態(tài)加載大量圖片,而且即使加載很大的圖片也不會使程序崩潰,前一種方式加載大圖片可能會出現(xiàn)問題
UIImage *image2 = [UIImage imageWithContentsOfFile:strPath];
// 通過制定URL得到的數(shù)據(jù)創(chuàng)建圖片對象
UIImage *image3 =[UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:@"https://www.baidu.com/img/bdlogo.png"]]];

5.image的幾種加載方式的選擇(性能優(yōu)化)
兩種取“本地圖片”的方式的區(qū)別
1.imageName:這種方法加載圖片相當(dāng)于做了一次單例的處理,適合于加載小圖標(biāo)小圖片等基本素材;其生命周期不會結(jié)束(單例相當(dāng)于全局變量);內(nèi)存不會釋放?
2.通過文件方式獲?。ㄟm合于加載大量圖片或動態(tài)圖片);內(nèi)存維持的比較好
imageWithContentsOfFile: