最近在項(xiàng)目中遇到要給一個(gè)圓形imgeView的底部增加一圈陰影,剛開(kāi)始這樣寫(xiě)是沒(méi)有出現(xiàn)陰影效果的,下面附上代碼:
_imgView.layer.cornerRadius = 75; //設(shè)置imageView的圓角
_imgView.layer.masksToBounds = YES;
_imgView.layer.shadowColor = [UIColor blackColor].CGColor;//設(shè)置陰影的顏色
_imgView.layer.shadowOpacity = 0.8;//設(shè)置陰影的透明度
_imgView.layer.shadowOffset = CGSizeMake(1, 1);//設(shè)置陰影的偏移量
_imgView.layer.shadowRadius = 3;//設(shè)置陰影的圓角
分析原因:因?yàn)榇a中設(shè)置了masksToBounds屬性為YES了,將后面設(shè)置的陰影效果給裁剪掉了,所以我們看不到陰影效果,如果我們將masksToBounds屬性為NO了,這樣就會(huì)失去圓角效果(盡管會(huì)出現(xiàn)陰影效果),所以需要向一個(gè)兩全其美的辦法來(lái)解決這個(gè)問(wèn)題。
給imageView添加一個(gè)父視圖,在父視圖上添加陰影效果就好,這樣就不會(huì)對(duì)imageView的圓角造成影響了。
UIView *shadowView = [[UIView alloc]initWithFrame:_imgView.frame];
[self.view addSubview:shadowView];
shadowView.layer.shadowColor = [UIColor blackColor].CGColor;
shadowView.layer.shadowOffset = CGSizeMake(5, 5);
shadowView.layer.shadowOpacity = 1;
shadowView.layer.shadowRadius = 9.0;
shadowView.layer.cornerRadius = 9.0;
shadowView.clipsToBounds = NO;
[shadowView addSubview:_imgView];
說(shuō)明:
clipsToBounds
是指視圖上的子視圖,如果超出父視圖的部分就截取掉,
masksToBounds
卻是指視圖的圖層上的子圖層,如果超出父圖層的部分就截取掉
最后附上效果圖
