美文网首页
[Swift] UIView+Extension

[Swift] UIView+Extension

作者: 巨馍蘸酱 | 来源:发表于2023-03-28 16:49 被阅读0次
    
    import UIKit
    
    public extension UIView {
        /// 获取 控件高度
        func heightToFit() -> CGFloat {
            self.setNeedsLayout()
            self.layoutIfNeeded()
            return self.systemLayoutSizeFitting(UIView.layoutFittingCompressedSize).height
        }
        
        /// 圆角
        func maskRadius(radius: CGFloat, corners: UIRectCorner) {
            guard self.bounds != CGRect.zero else { return }
            
            let bezierPath = UIBezierPath(roundedRect: self.bounds, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: radius))
            let shapeLayer = CAShapeLayer()
            shapeLayer.frame = self.bounds
            shapeLayer.path = bezierPath.cgPath
            self.layer.mask = shapeLayer
        }
        
        /// 边框 + 圆角
        func maskBorder(radius: CGFloat, corners: UIRectCorner, fillColor: UIColor, strokeColor: UIColor, borderWidth: CGFloat) {
            guard self.bounds != CGRect.zero else { return }
            
            let bezierPath = UIBezierPath(roundedRect: self.bounds, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: radius))
            
            let shapeLayer = CAShapeLayer()
            shapeLayer.frame = self.bounds
            shapeLayer.path = bezierPath.cgPath
            self.layer.mask = shapeLayer
            
            let borderLayer = CAShapeLayer()
            borderLayer.frame = self.bounds
            borderLayer.path = bezierPath.cgPath
            borderLayer.lineWidth = borderWidth
            borderLayer.fillColor = fillColor.cgColor
            borderLayer.strokeColor = strokeColor.cgColor
            self.layer.addSublayer(borderLayer)
        }
        
        /// 渐变色
        func addGradientLayer(start: UIColor, end: UIColor) {
            let gradientLayer = CAGradientLayer()
            gradientLayer.startPoint = CGPoint(x: 0, y: 0)
            gradientLayer.endPoint = CGPoint(x: 0, y: 1)
            gradientLayer.locations = [0, 1]
            gradientLayer.colors = [start.cgColor, end.cgColor]
            self.layer.addSublayer(gradientLayer)
        }
        
    }
    
    

    相关文章

      网友评论

          本文标题:[Swift] UIView+Extension

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