1.UIImageView与UIImage的区别
UIImageView:这是UI控件,继承自UIView,是用来显示图片的控件,UIImageView中有一个UIImage类型的属性——image,用来存放需要显示的图片。
UIImage:可以理解为是图片文件,文件是不能显示的,文件相当于保存在磁盘上的一堆二进制编码。UIImage的父类是NSObject。创建UIImage对象可以使用imageNamed:以及imageWithContentsOfFile:方法,区别在于需要传入的图片文件的路径不同。
+(nullable UIImage *)imageNamed:(NSString *)name; // 从Assets文件夹中加载文件
+(nullable UIImage *)imageWithContentsOfFile:(NSString *)path; // 从应用的资源文件夹中加载图片
// UIImageView对象的创建
-(void)viewDidLoad {
[super viewDidLoad];
UIImageView *imageView = [[UIImageView alloc] init] initWithFrame:CGRectMake(80, 50, 200, 200)];
imageView.image = [UIIMage imageNamed:@"logo"];
[self.view addSubview:imageView];
}
2 常用操作
设置圆角/圆形头像
-(void)viewDidLoad {
[super viewDidLoad];
//
UIImageView *imageView = [[UIImageView alloc] initWithCGRectMake(80, 50, 200, 200)];
imageView.image = [UIImage imageNamed:@"logo"];
// 设置圆角
imageView.layer.cornerRedius = 5;
imageView.layer.masksToBounds = YES;
// 设置边框
imageView.layer.borderWidth = 5;
imageView.layer.borderColor = [UIColor redColor].CGColor;
[self.view addSubview:imageView];
}
// 默认情况下,UIImageView对象是不能够响应用户交互的,这是因为在UIImageView类中其userInteractionEnabled属性的默认取值为NO。这里可以修改该属性的值,并且为该UIImageView对象添加手势后,即可响应用户交互。
@property (nonatomic, getter=isUserInteractionEnabled) BOOL userInteractionEnabled;
-(void)viewDidLoad {
// ...
// 添加手势
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tap:)];
[imageView addGestureRecognizer:tap];
imageView.userInteractionEnabled = YES;
// ...
}
3 帧动画功能
1.UIImageView动画播放相关属性与方法
// 图片存放的数组。把所有需要播放的图片有序地放到该数组中。
@property (nullable, nonatomic, copy) NSArray *animationImage;
// 动画播放的时长,默认取值为:animationImages中图片的数量*1/30。
@property (nullable) NSTimeInterval animationDuration;
// 动画播放次数
@property (nullable) NSInteger animationRepeatCount;
//
-(void)startAnimating; // 开始播放
-(void)stopAnimating; // 停止播放
-(BOOL)isAnimating; // 是否在播放
2.自动清除
// 由于animationImages数组会在内存中保存大量的图片,且动画播放完毕后不会自动销毁,所以会一直占用较大的内存,因此,动画播放完毕后需要自动清除该属性中保存的图片。
// 通常的操作方式是在动画播放完成后,把该数组指向nil。
// 动画播放完毕0.1秒后,清空图片占用内存。
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)((imageView.animationImage.count *0.08 + 0,1)*NSEC_PRE_SEC)), dispatch_get_main_queue(), ^{
imageView.animationImages = nil;
});