1. 程式人生 > >iOS 檢視切圓角和陰影

iOS 檢視切圓角和陰影

1.四個角都切

self.picImage.layer.cornerRadius = 8;

self.picImage.layer.masksToBounds = YES;

2.切1~4個角

程式碼示例(切的左下,和右下)

UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:self.tipLabel.bounds byRoundingCorners:UIRectCornerBottomLeft | UIRectCornerBottomRight cornerRadii:CGSizeMake(5
, 5)]; CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init]; maskLayer.frame = _tipLabel.bounds; maskLayer.path = maskPath.CGPath; self.tipLabel.layer.mask = maskLayer;

型別共有以下幾種:

  • UIRectCornerTopLeft

  • UIRectCornerTopRight

  • UIRectCornerBottomLeft

  • UIRectCornerBottomRight

  • UIRectCornerAllCorners

3.檢視加陰影

  • 陰影的顏色
    imgView.layer.shadowColor = [UIColor blackColor].CGColor;
  • 陰影的透明度
    imgView.layer.shadowOpacity = 0.8f;
  • 陰影的圓角
    imgView.layer.shadowRadius = 4.f;
  • 陰影偏移量
    imgView.layer.shadowOffset = CGSizeMake(5,5);

這裡寫圖片描述

imgView.layer.shadowOffset = CGSizeMake(0,0);

這裡寫圖片描述

4.圓角和陰影共存

圓角和陰影無法在一個layer上共存,所以需要思路是再建立一個layer層,實現陰影,放到檢視下邊,具體實現:

//圓角
imgView.layer.masksToBounds = YES;
imgView.layer.cornerRadius = 10;
// 陰影
CALayer *subLayer=[CALayer layer];
    CGRect fixframe = imgView.frame;
    subLayer.frame= fixframe;
    subLayer.cornerRadius=8;
    subLayer.backgroundColor=[[UIColor blackColor] colorWithAlphaComponent:0.8].CGColor;
    subLayer.masksToBounds=NO;
    subLayer.shadowColor = [UIColor blackColor].CGColor;//shadowColor陰影顏色
    subLayer.shadowOffset = CGSizeMake(3,2);//shadowOffset陰影偏移,x向右偏移3,y向下偏移2,預設(0, -3),這個跟shadowRadius配合使用
    subLayer.shadowOpacity = 0.8;//陰影透明度,預設0
    subLayer.shadowRadius = 4;//陰影半徑,預設3
    [self.view.layer insertSublayer:subLayer below:imgView.layer];

這裡寫圖片描述

轉載請註明出處,萬分感謝!