1:四個角都設置圓角
方法1:
通過設置layer的屬性,也是最簡單的一種方法
UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(100, 100, 100, 100)]; imageView.layer.cornerRadius = imageView.frame.size.width / 2; imageView.layer.masksToBounds = YES; [self.view addSubview:imageView];
方法2:
使用貝塞爾曲線UIBezierPath和Core Graphics框架畫出一個圓角
UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(100, 100, 100, 100)]; imageView.image = [UIImage imageNamed:@"1"]; //開始對imageView進行畫圖 UIGraphicsBeginImageContextWithOptions(imageView.bounds.size, NO, 1.0); //使用貝塞爾曲線畫出一個圓形圖 [[UIBezierPath bezierPathWithRoundedRect:imageView.bounds cornerRadius:imageView.frame.size.width] addClip]; [imageView drawRect:imageView.bounds]; imageView.image = UIGraphicsGetImageFromCurrentImageContext(); //結(jié)束畫圖 UIGraphicsEndImageContext(); [self.view addSubview:imageView];
方法3
使用CAShapeLayer和UIBezierPath設置圓角
UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(100, 100, 100, 100)]; imageView.image = [UIImage imageNamed:@"1"]; UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:imageView.bounds byRoundingCorners:UIRectCornerAllCorners cornerRadii:imageView.bounds.size]; CAShapeLayer *maskLayer = [[CAShapeLayer alloc]init]; //設置大小 maskLayer.frame = imageView.bounds; //設置圖形樣子 maskLayer.path = maskPath.CGPath; imageView.layer.mask = maskLayer; [self.view addSubview:imageView];
2:設置某幾個角為圓角
其實可以用上邊的第三種方法做
UIView *view2 = [[UIView alloc] initWithFrame:CGRectMake(120, 10, 80, 80)]; view2.backgroundColor = [UIColor redColor]; [self.view addSubview:view2]; UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:view2.bounds byRoundingCorners:UIRectCornerBottomLeft | UIRectCornerBottomRight cornerRadii:CGSizeMake(10, 10)]; CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init]; maskLayer.frame = view2.bounds; maskLayer.path = maskPath.CGPath; view2.layer.mask = maskLayer;
其中,byRoundingCorners:UIRectCornerBottomLeft | UIRectCornerBottomRight
指定了需要成為圓角的角。該參數(shù)是UIRectCorner類型的,可選的值有:
- UIRectCornerTopLeft
- UIRectCornerTopRight
- UIRectCornerBottomLeft
- UIRectCornerBottomRight
- UIRectCornerAllCorners
從名字很容易看出來代表的意思,使用“|”來組合就好了。