iOS头像效果的实现(边框、阴影、可点击)

一、目的:实现一个带有立体感效果的头像效果

二、效果图:

三、组成介绍:

     1、一个UIImageView (用来显示照片的)

     2、CALayer       (用来显示背景的阴影效果)

     3、手势       (点击照片有反应,可以添加一些查看头像以及改头像的效果)  

四、代码如下:

 1     //添加一个圆形图片,带内边框
 2       UIImageView *headImage=[[UIImageView alloc]initWithFrame:CGRectMake(100, 100, 100, 100)];
 3       [headImage setBackgroundColor:[UIColor blueColor]];
 4       headImage.layer.cornerRadius=50;      //设置圆形效果是根据这个imageVeiw的宽度来设定的
 5       headImage.image=[UIImage imageNamed:@"image.png"];
 6       headImage.contentMode=UIViewContentModeScaleAspectFill;
 7       headImage.clipsToBounds=YES;         //这里必须设置将图片剪切成圆形,而阴影效果是在园外的,所以不可以在这个ImageView添加阴影
 8       headImage.layer.borderWidth=3;        //虽然不可以添加阴影效果,但是可以添加一个内边框效果,感觉蛮好看的
 9       headImage.layer.borderColor=[UIColor colorWithRed:1.0 green:1.0 blue:1.0 alpha:0.6].CGColor;//设置颜色和透明度
10      [self.view addSubview:headImage];
11      //添加背景
12      CALayer *layer=[[CALayer alloc]init];
13      layer.position=headImage.layer.position;        //这里是个人喜好这么写
14      layer.bounds=headImage.bounds;
15      layer.cornerRadius=headImage.layer.cornerRadius;
16      layer.backgroundColor=[UIColor blackColor].CGColor;  //这里必须设置layer层的背景颜色,默认应该是透明的,导致设置的阴影颜色无法显示出来
17      layer.shadowColor=[UIColor grayColor].CGColor;     //设置阴影的颜色
18      layer.shadowRadius=5;               //设置阴影的宽度
19      layer.shadowOffset=CGSizeMake(2, 2);      //设置偏移
20      layer.shadowOpacity=1;
21      [self.view.layer addSublayer:layer];
22      [self.view bringSubviewToFront:headImage];
23      //添加手势
24      UITapGestureRecognizer *tap=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(clickedTheImage)];//响应方法没写
25     headImage.userInteractionEnabled=YES;   ///必须设置用户交互,手势才有用
26      [headImage addGestureRecognizer:tap];

五⚠️、总结和注意事项  

     1.给imageView添加了图片并且设置了clipsToBounds后不可显示外部的阴影效果了,因为阴影效果就是在外部设置的,一经剪切就没有了,所以要再加一个CALayer来显示这个阴影效果。
     2.给imgeView添加图片时要设置clipsToBounds=YES;这样才可以将图片设置为圆形;
     3.imageView的边界效果是
          headImage.layer.borderWidth=3;
          headImage.layer.borderColor=[UIColor colorWithRed:1.0 green:1.0 blue:1.0 alpha:0.6].CGColor;
     4.要在CALayer层显示阴影效果,必须设置CALayer的背景颜色
     5.添加CALayer层之后要将ImageView设置到最前端
     6.手势添加后要设置手势的交互,不然不能响应
          headImage.userInteractionEnabled=YES;

(作者原创) 

原文地址:https://www.cnblogs.com/CF-STRONG/p/5049941.html