iOS 实现视图指定圆角

需求

  • 可以设置单独设置视图的某个圆角
  • 可以设置几个指定的圆角
  • 可以设置是否绘制边框、边框宽度

实现原理

使用贝塞尔曲线实现

代码

由于不是很复杂,所以就直接贴上代码

复制代码
import UIKit

@IBDesignable
public class CornerView: UIView {

    @IBInspectable public var drawBorder: Bool = false
    @IBInspectable public var borderWidth: CGFloat = 1.0
    @IBInspectable public var topCornerRadius: CGFloat = 10.0
    @IBInspectable public var topLeft: Bool = false
    @IBInspectable public var topRight: Bool = false
    @IBInspectable public var bottomLeft: Bool = false
    @IBInspectable public var bottomRight: Bool = false
    
    public override init(frame: CGRect) {
        super.init(frame: frame)
    }
    
    public required init?(coder: NSCoder) {
        super.init(coder: coder)
    }
    
    public override func draw(_ rect: CGRect) {
        super.draw(rect)
        
        var corners: UInt = 0
        if self.topLeft == true {
            corners = corners | UIRectCorner.topLeft.rawValue
        }
        
        if self.topRight == true {
            corners = corners | UIRectCorner.topRight.rawValue
        }
        
        if self.bottomRight == true {
            corners = corners | UIRectCorner.bottomRight.rawValue
        }
        
        if self.bottomLeft == true {
            corners = corners | UIRectCorner.bottomLeft.rawValue
        }
        
        let topCorner: UIRectCorner = UIRectCorner(rawValue: corners)
        
        // 绘制圆角
        let path = UIBezierPath(roundedRect: self.bounds, byRoundingCorners: topCorner, cornerRadii: CGSize(width: self.topCornerRadius, height: self.topCornerRadius))
        let maskLayer = CAShapeLayer()
        
        maskLayer.frame = self.bounds
        maskLayer.path = path.cgPath
        
        if drawBorder == true {
            // 绘制边框
            UIBezierPath.drawRightTopCornerBorder(width: self.width, cornerRadius: self.topCornerRadius, lineWidth: self.borderWidth, cornerColor: .white)
            UIBezierPath.drawLeftTopCornerBorder(cornerRadius: self.topCornerRadius, lineWidth: self.borderWidth, cornerColor: .white)
        }
        
        self.layer.mask = maskLayer
    }
    
    public override func layoutSubviews() {
        super.layoutSubviews()
    }
    
}
复制代码

 

posted @   sims  阅读(21)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
点击右上角即可分享
微信分享提示