第一種方法:通過設置layer的屬性
最簡單的一種,但是很影響性能,一般在正常的開發中使用很少.
lable.clipsToBounds = YES;(耗內存)
lable.layer.cornerRadius = 50;
第二種方法:通過UIGraphics和貝塞爾曲線進行繪制
UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(100, 400, 100, 100)];
imageView.image = [UIImage imageNamed:@"ask"];
imageView.image = [self imageWithCornerRadius:50 withImageView:imageView];
[self.view addSubview:imageView];
- (UIImage *)imageWithCornerRadius:(CGFloat)radius withImageView:(UIImageView *)imageView{
CGRect rect = (CGRect){0.f, 0.f, imageView.frame.size};
UIGraphicsBeginImageContextWithOptions(imageView.frame.size, NO, UIScreen.mainScreen.scale);
CGContextAddPath(UIGraphicsGetCurrentContext(),[UIBezierPath bezierPathWithRoundedRect:rect cornerRadius:radius].CGPath);
CGContextClip(UIGraphicsGetCurrentContext());
[imageView.image drawInRect:rect];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
第三種方法:使用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];