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;

 

(作者原創) 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM