UIImageView控件:2-常用操作
当创建完成一个UIImageView对象后,通常情况下,我们会对其样式进行一些定制,例如,裁剪UIImageView对象的边角,添加边框,添加手势等等。
设置圆角/圆形头像
默认情况下,UIImageView是一个矩形,其边角是没有圆滑过渡的,在实际的开发过程中,我们经常需要把图片的边角设置为圆角,此时可以通过修改UIImageView的layer属性实现。
- (void)viewDidLoad {
[super viewDidLoad];
//初始化UIImageView对象
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(80, 50, 200, 200)];
imageView.image = [UIImage imageNamed:@"99logo"];
//设置圆角
imageView.layer.cornerRadius = 5;
imageView.layer.masksToBounds = YES;
//添加到控制器view
[self.view addSubview:imageView];
}
通过上面的方法,当我们设置cornerRadius的值为UIImageView宽度的一半时,最终展示的就是一个圆形的图片,如下所示。
设置边框
UIImageView对象创建后,默认情况下是没有边框的,我们可以通过修改layer的borderWidth以及borderColor来设置UIImageView的边框属性。
- (void)viewDidLoad {
[super viewDidLoad];
//初始化UIImageView对象
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(80, 50, 200, 200)];
imageView.image = [UIImage imageNamed:@"99logo"];
//设置边框
imageView.layer.borderWidth = 5;
imageView.layer.borderColor = [UIColor redColor].CGColor;
//添加到控制器view
[self.view addSubview:imageView];
}
运行结果。
添加手势点击事件
默认情况下,UIImageView对象是不能够响应用户交互的,这是因为在UIImageView类中其userInteractionEnabled属性的默认取值为NO。我们可以修改该属性的值,并且为该UIImageView对象添加手势后,即可响应用户交互。
@property (nonatomic, getter=isUserInteractionEnabled) BOOL userInteractionEnabled;
下方的示例代码中为imageView对象添加了一个点击手势。
- (void)viewDidLoad {
[super viewDidLoad];
//初始化UIImageView对象
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(80, 50, 200, 200)];
imageView.image = [UIImage imageNamed:@"99logo"];
//添加手势
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tap:)];
[imageView addGestureRecognizer:tap];
imageView.userInteractionEnabled = YES;
//添加到控制器view
[self.view addSubview:imageView];
}
示例代码
https://github.com/99ios/7.3.2
文章发布时间为: August 8th , 2016 at 08:21 pm
最后编辑时间为: September 14th , 2017 at 10:05 am
本文由 99ios 创作,转载请注明出处
最后编辑时间为: September 14th , 2017 at 10:05 am
本文由 99ios 创作,转载请注明出处