如何在iOS Swift中为UIView的不同角设置不同圆角半径?
为UIView设置不同圆角半径的Swift实现
这个问题我做项目时也踩过坑!直接用layer.cornerRadius确实只能给所有角设同一个值,每次设置还会覆盖之前的配置,要实现四个角分别用不同半径的效果,得靠自定义图层遮罩来搞定,下面给你两种实用的实现方案:
方案一:通用自定义遮罩(支持所有iOS版本)
我写了一个UIView的扩展,通过手动绘制UIBezierPath来创建不同圆角的路径,再把这个路径作为图层遮罩应用到View上:
extension UIView { func setCustomCornerRadii(topLeft: CGFloat, topRight: CGFloat, bottomLeft: CGFloat, bottomRight: CGFloat) { // 手动构建带有不同圆角的路径 let path = UIBezierPath() // 从左上角圆角的右端点开始绘制 path.move(to: CGPoint(x: bounds.minX + topLeft, y: bounds.minY)) // 绘制右上角的圆弧 path.addArc(withCenter: CGPoint(x: bounds.maxX - topRight, y: bounds.minY + topRight), radius: topRight, startAngle: .pi * 3/2, endAngle: 0, clockwise: true) // 绘制右下角的圆弧 path.addArc(withCenter: CGPoint(x: bounds.maxX - bottomRight, y: bounds.maxY - bottomRight), radius: bottomRight, startAngle: 0, endAngle: .pi/2, clockwise: true) // 绘制左下角的圆弧 path.addArc(withCenter: CGPoint(x: bounds.minX + bottomLeft, y: bounds.maxY - bottomLeft), radius: bottomLeft, startAngle: .pi/2, endAngle: .pi, clockwise: true) // 绘制左上角的圆弧并闭合路径 path.addArc(withCenter: CGPoint(x: bounds.minX + topLeft, y: bounds.minY + topLeft), radius: topLeft, startAngle: .pi, endAngle: .pi * 3/2, clockwise: true) path.close() // 创建遮罩图层并应用 let maskLayer = CAShapeLayer() maskLayer.path = path.cgPath layer.mask = maskLayer } }
使用方式
直接给你的UIView调用这个方法就行:
// 示例:创建一个View并设置不同圆角 let customView = UIView(frame: CGRect(x: 60, y: 60, width: 220, height: 220)) customView.backgroundColor = .systemBlue // 按需求设置四个角的半径:topLeft=1, topRight=5, bottomLeft=10, bottomRight=15 customView.setCustomCornerRadii(topLeft: 1, topRight: 5, bottomLeft: 10, bottomRight: 15) view.addSubview(customView)
注意事项
如果你的View是用AutoLayout布局的,记得在layoutSubviews里重新调用这个方法(因为View的bounds会在布局更新后变化),可以写个自定义View来简化:
class CustomCornerView: UIView { // 定义一个存储圆角参数的属性,修改时自动触发布局更新 var cornerRadii: (topLeft: CGFloat, topRight: CGFloat, bottomLeft: CGFloat, bottomRight: CGFloat) = (0,0,0,0) { didSet { setNeedsLayout() } } override func layoutSubviews() { super.layoutSubviews() setCustomCornerRadii(topLeft: cornerRadii.topLeft, topRight: cornerRadii.topRight, bottomLeft: cornerRadii.bottomLeft, bottomRight: cornerRadii.bottomRight) } }
方案二:iOS 13+简化思路(仅支持分组圆角)
如果你的项目只需要支持iOS 13及以上,且只是部分角分组设置相同半径(比如左上右上一组,左下右下一组),可以用layer.cornerRadius结合maskedCorners,但这个方法没法实现四个角全不同的效果,仅作补充:
// 示例:左上和右上设为5,左下和右下设为10 let myView = UIView(frame: CGRect(x: 60, y: 60, width: 220, height: 220)) myView.backgroundColor = .systemGreen myView.layer.cornerRadius = 5 myView.layer.maskedCorners = [.layerMinXMinYCorner, .layerMaxXMinYCorner] // 左上、右上 // 若要设置另外两个角,需要额外处理,但无法实现四个角全不同,所以四个角不同的场景还是推荐方案一
为什么常规cornerRadius不行?
layer.cornerRadius是一个全局属性,作用于View的所有四个角,每次设置都会覆盖之前的圆角配置,没办法单独指定单个角的半径值,所以必须通过自定义路径遮罩的方式,才能实现不同角的不同圆角效果。
内容的提问来源于stack exchange,提问作者Ganesh Kakade
相关产品推荐
相关产品推荐

