UIButton边界的生涩渐变

问题描述 投票:0回答:1

我需要在边框中创建带渐变的圆角UIButton。我在Core Graphics代码中错过了什么?

我用面具创建了CAGradientLayer。

        layer.cornerRadius = 43
        let gradient = CAGradientLayer()
        gradient.frame = bounds
        gradient.colors = [UIColor(red: 0.99, green: 0.89, blue: 0.54, alpha: 1).cgColor, UIColor(red: 0.95, green: 0.51, blue: 0.51, alpha: 1).cgColor]
        gradient.locations = [0, 1]
        gradient.startPoint = CGPoint(x: 1.83, y: -0.68)
        gradient.endPoint = CGPoint(x: 0.13, y: 0.82)
        gradient.cornerRadius = 43

        let shape = CAShapeLayer()
        shape.lineWidth = 6
        shape.path = UIBezierPath(roundedRect: gradient.frame, cornerRadius: 43).cgPath
        shape.strokeColor = UIColor.black.cgColor
        shape.fillColor = UIColor.clear.cgColor
        gradient.mask = shape

        layer.addSublayer(gradient)
        setTitleColor(.red, for: .normal)
        titleLabel?.font = Theme.shared.font.bold(ofSize: 25.0)
        clipsToBounds = true

我期待不是生涩的渐变,被面具均匀地修剪。

enter image description here

ios swift uibutton core-graphics tvos
1个回答
0
投票

第一个问题是路径的边框以帧的边缘为中心,因此您需要将路径插入线宽的1/2。

第二个问题是设置图层的.cornerRadius不会给出与圆形rect bezier路径相同的曲线(奇数,但情况就是这样)。因此,您需要创建另一个蒙版以应用于按钮的图层。它可能会在边缘产生伪影,因此将其插入0.5点。

试试这个修改后的代码

    // create gradient layer
    let gradient = CAGradientLayer()
    gradient.frame = bounds
    gradient.colors = [UIColor(red: 0.99, green: 0.89, blue: 0.54, alpha: 1).cgColor, UIColor(red: 0.95, green: 0.51, blue: 0.51, alpha: 1).cgColor]
    gradient.locations = [0, 1]
    gradient.startPoint = CGPoint(x: 1.83, y: -0.68)
    gradient.endPoint = CGPoint(x: 0.13, y: 0.82)

    // create shape for gradient layer mask
    let gradientShape = CAShapeLayer()

    // edge / line width of 6
    gradientShape.lineWidth = 6

    // border is centered on the edge, so we want to inset the rect by 1/2 of the border width
    var r = bounds.insetBy(dx: 3, dy: 3)

    // create rounded rect path
    gradientShape.path = UIBezierPath(roundedRect: r, cornerRadius: 43).cgPath

    // black stroke, clear fill
    gradientShape.strokeColor = UIColor.black.cgColor
    gradientShape.fillColor = UIColor.clear.cgColor

    // assign the shape as the gradient layer's mask
    gradient.mask = gradientShape

    // create a new shape for the button's layer
    let layerShape = CAShapeLayer()

    // inset by 0.5, to avoid artifacts on the edges
    r = bounds.insetBy(dx: 0.5, dy: 0.5)

    // create rounded rect path
    layerShape.path = UIBezierPath(roundedRect: r, cornerRadius: 43).cgPath

    // black fill (no stroke)
    layerShape.fillColor = UIColor.black.cgColor

    // assign the shape as the layer's mask
    layer.mask = layerShape

    // add gradient layer as a sublayer
    layer.addSublayer(gradient)

    setTitleColor(.red, for: .normal)
    titleLabel?.font = Theme.shared.font.bold(ofSize: 25.0)
    clipsToBounds = true
© www.soinside.com 2019 - 2024. All rights reserved.