首页 文章

在自定义UIView边框上设置渐变颜色

提问于
浏览
0

我有一个 UIView ,其中包含一个带有按钮的2 UILabels ,我想为它的边框添加渐变颜色 . 我已经设法添加它,并且按钮已经移动到自定义 UIView 之外,自定义 UIView 也在较小的设备上一直缩小 . 当我添加 gradient color 时,如何修复 UIView 以保持相同的大小

这是最初的 UIView ,其中有两个 UILabels 和一个内部带有正常边框颜色的按钮

这里是应用渐变颜色后的样子

这是我如何应用渐变的代码 .

@IBOutlet weak var customView: UIView!

let gradient = CAGradientLayer()
        gradient.frame.size = self.customView.frame.size
        gradient.colors = [UIColor.green.cgColor, UIColor.yellow.cgColor, UIColor.red.cgColor]
        gradient.startPoint = CGPoint(x: 0.1, y: 0.78)
        gradient.endPoint = CGPoint(x: 1.0, y: 0.78)
        let shapeLayer = CAShapeLayer()
        shapeLayer.path = UIBezierPath(rect:   self.customView.bounds).cgPath
        shapeLayer.fillColor = UIColor.clear.cgColor
        shapeLayer.strokeColor = UIColor.black.cgColor
        shapeLayer.lineWidth = 4
        gradient.mask = shapeLayer
        self.customView.layer.addSublayer(gradient)

1 回答

  • 2

    视图调整大小时图层不会调整大小,因此您要创建自定义视图并覆盖 layoutSubviews() .

    这是一个例子:

    @IBDesignable
    class GradBorderView: UIView {
    
        var gradient = CAGradientLayer()
    
        override init(frame: CGRect) {
            super.init(frame: frame)
            commonInit()
        }
    
        required init?(coder aDecoder: NSCoder) {
            super.init(coder: aDecoder)
            commonInit()
        }
    
        func commonInit() -> Void {
            layer.addSublayer(gradient)
        }
    
        override func layoutSubviews() {
    
            gradient.frame = bounds
            gradient.colors = [UIColor.green.cgColor, UIColor.yellow.cgColor, UIColor.red.cgColor]
            gradient.startPoint = CGPoint(x: 0.1, y: 0.78)
            gradient.endPoint = CGPoint(x: 1.0, y: 0.78)
            let shapeLayer = CAShapeLayer()
            shapeLayer.path = UIBezierPath(rect: bounds).cgPath
            shapeLayer.fillColor = UIColor.clear.cgColor
            shapeLayer.strokeColor = UIColor.black.cgColor
            shapeLayer.lineWidth = 4
            gradient.mask = shapeLayer
    
        }
    
    }
    

    现在,当您的视图根据约束和自动布局更改大小时,渐变边框将正确“自动调整大小” .

    此外,通过使用 @IBDesignable ,您可以在Storyboard / Interface Builder中布局视图时查看结果 .

    以下是 Grad Border View 宽度设置为 240 时的外观:

    并且 Grad Border View 宽度设置为 320

相关问题