美文网首页
Swift UIview常用的扩展方法、圆角(1)

Swift UIview常用的扩展方法、圆角(1)

作者: 难猿 | 来源:发表于2023-03-29 19:56 被阅读0次

圆角是 iOS 开发中非常常见的需求,但是普通的圆角实现会比较消耗性能,特别是在滚动视图中会出现卡顿的情况。下面介绍两种高性能的圆角实现方式。

方案一:使用 CAShapeLayer

这种方法使用 CAShapeLayer 和贝塞尔曲线来实现圆角效果,具有很高的性能和可定制性。

示例代码:

extension UIView {
    func addCornerRadius(_ radius: CGFloat) {
        let path = UIBezierPath(roundedRect: self.bounds, cornerRadius: radius)
        let shape = CAShapeLayer()
        shape.path = path.cgPath
        self.layer.mask = shape
    }
}

使用时,只需要调用该方法并传入需要的圆角半径即可:

myView.addCornerRadius(10)

方案二:使用 UIImageView 和 Core Graphics

这种方法使用 UIImageView 和 Core Graphics 来实现圆角效果,相对来说会消耗更多的内存,但是在某些情况下可能比第一种方法更高效。

extension UIView {
    func addCornerRadius(_ radius: CGFloat) {
        let imageView = UIImageView(frame: self.bounds)
        imageView.image = self.snapshot
        imageView.layer.cornerRadius = radius
        imageView.layer.masksToBounds = true
        self.addSubview(imageView)
    }
    
    var snapshot: UIImage? {
        UIGraphicsBeginImageContextWithOptions(bounds.size, isOpaque, 0.0)
        drawHierarchy(in: bounds, afterScreenUpdates: true)
        let snapshotImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return snapshotImage
    }
}

该方法先创建一个 UIImageView,并将当前视图的快照设置为其 image 属性,然后对该 UIImageView 应用圆角效果。需要注意的是,该方法在获取快照时会消耗一些性能和内存。

使用时,只需要调用该方法并传入需要的圆角半径即可:

myView.addCornerRadius(10)

这两种方法都可以用于任何 UIView 的子类,例如 UIButton、UILabel、UIImageView 等等。需要根据具体情况选择合适的方法来实现圆角效果。

相关文章

网友评论

      本文标题:Swift UIview常用的扩展方法、圆角(1)

      本文链接:https://www.haomeiwen.com/subject/fiafddtx.html