一:通过设置layer属性,主要是cornerRadius和masksToBounds属性,但是这种方式影响性能,不推荐使用。
二:使用贝塞尔曲线UIBezierPath和Core Graphics框架画出一个圆角
// swift
let imgView = UIImageView()
imgView.frame = CGRect(x: 50, y: 100, width: UIScreen.main.bounds.width - 100, height: 300)
imgView.image = UIImage(named: "timg.jpeg")
//开始对imageView进行画图
UIGraphicsBeginImageContextWithOptions(imgView.bounds.size, false, 1.0)
//使用贝塞尔曲线画出一个圆形图
UIBezierPath(roundedRect: imgView.bounds, cornerRadius: 20).addClip()
imgView.draw(imgView.bounds)
imgView.image = UIGraphicsGetImageFromCurrentImageContext()
// 结束画图
UIGraphicsEndImageContext()
view.addSubview(imgView)
// OC
UIImageView * imgView = [[UIImageView alloc] init];
imgView.frame = CGRectMake(50, 100, UIScreen.mainScreen.bounds.size.width - 100, 300);
imgView.image = [UIImage imageNamed:@"timg.jpeg"];
//开始对imageView进行画图
UIGraphicsBeginImageContextWithOptions(imgView.bounds.size, NO, 1.0);
//使用贝塞尔曲线画出一个圆形图
[[UIBezierPath bezierPathWithRoundedRect:imgView.bounds cornerRadius:20] addClip];
[imgView drawRect:imgView.bounds];
imgView.image = UIGraphicsGetImageFromCurrentImageContext();
//结束画图
UIGraphicsEndImageContext();
[self.view addSubview:imgView];
三:使用CAShapeLayer和UIBezierPath设置圆角
// swift
let imgView1 = UIImageView()
imgView1.frame = CGRect(x: 50, y: 420, width: UIScreen.main.bounds.width - 100, height: 300)
imgView1.image = UIImage(named: "timg.jpeg")
let maskPath = UIBezierPath(roundedRect: imgView1.bounds, byRoundingCorners: .allCorners, cornerRadii: CGSize(width: 20, height: 20))
let maskLayer = CAShapeLayer()
// 设置大小
maskLayer.frame = imgView1.bounds
// 设置图形样子
maskLayer.path = maskPath.cgPath
imgView1.layer.mask = maskLayer
view.addSubview(imgView1)
// OC
UIImageView * imgView1 = [[UIImageView alloc] init];
imgView1.frame = CGRectMake(50, 420, UIScreen.mainScreen.bounds.size.width - 100, 300);
imgView1.image = [UIImage imageNamed:@"timg.jpeg"];
UIBezierPath * maskPath = [UIBezierPath bezierPathWithRoundedRect:imgView1.bounds byRoundingCorners:UIRectCornerAllCorners cornerRadii:CGSizeMake(20, 20)];
CAShapeLayer * maskLayer = [[CAShapeLayer alloc] init];
// 设置大小
maskLayer.frame = imgView1.bounds;
// 设置图形样子
maskLayer.path = maskPath.CGPath;
imgView1.layer.mask = maskLayer;
[self.view addSubview:imgView1];