我想在UIView中使用从左到右的渐变来设置边框颜色[红色,绿色]。
像例子:

ios - 如何在Swift 4的UIView中创建带有圆角的渐变边界-LMLPHP

我尝试了以下代码:-

class View: UIView {

    override func layoutSubviews() {
        super.layoutSubviews()

        let path = UIBezierPath(roundedRect: self.bounds, byRoundingCorners: [.topLeft, .bottomLeft, .topRight, .bottomRight], cornerRadii: CGSize(width: frame.size.height / 2, height: frame.size.height / 2))

        let gradient = CAGradientLayer()
        gradient.frame =  CGRect(origin: CGPoint.zero, size: frame.size)
        gradient.colors = [UIColor.green.cgColor, UIColor.red.cgColor]

        let shape = CAShapeLayer()
        shape.lineWidth = 10
        shape.path = path.cgPath
        shape.strokeColor = UIColor.black.cgColor
        shape.fillColor = UIColor.clear.cgColor
        gradient.mask = shape

        layer.insertSublayer(gradient, at: 0)
    }
}

我无法解决三个问题:-
1- 我设置了lineWidth 10,但是它在拐角处和水平/垂直处仅显示宽度10。
2- 我想显示从左到右而不是从上到下的渐变。

我试过下面的代码来设置从左到右的渐变,但不起作用:-
//        gradient.frame =  CGRect(origin: CGPoint.zero, size: frame.size)
        gradient.startPoint = CGPoint(x: 0.0, y: 0.5)
        gradient.endPoint = CGPoint(x: 1.0, y: 0.5)

ios - 如何在Swift 4的UIView中创建带有圆角的渐变边界-LMLPHP

请帮忙。提前致谢。

最佳答案

编辑

我想从左到右设置边框

您需要更改gradient.startPoint和gradient.endPoint

enum Direction {
    case horizontal
    case vertical
}

class View: UIView {

init(frame: CGRect, cornerRadius: CGFloat, colors: [UIColor], lineWidth: CGFloat = 5, direction: Direction = .horizontal) {
    super.init(frame: frame)

    self.layer.cornerRadius = cornerRadius
    self.layer.masksToBounds = true
    let gradient = CAGradientLayer()
    gradient.frame = CGRect(origin: CGPoint.zero, size: self.frame.size)
    gradient.colors = colors.map({ (color) -> CGColor in
        color.cgColor
    })

    switch direction {
    case .horizontal:
        gradient.startPoint = CGPoint(x: 0, y: 1)
        gradient.endPoint = CGPoint(x: 1, y: 1)
    case .vertical:
        gradient.startPoint = CGPoint(x: 0, y: 0)
        gradient.endPoint = CGPoint(x: 0, y: 1)
    }

    let shape = CAShapeLayer()
    shape.lineWidth = lineWidth
    shape.path = UIBezierPath(roundedRect: self.bounds.insetBy(dx: lineWidth,
    dy: lineWidth), cornerRadius: cornerRadius).cgPath
    shape.strokeColor = UIColor.black.cgColor
    shape.fillColor = UIColor.clear.cgColor
    gradient.mask = shape

    self.layer.addSublayer(gradient)
}

required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}

如您所见,我添加了一些额外的参数。我通过在roundedRect中添加inset解决了这个问题:
shape.path = UIBezierPath(roundedRect: self.bounds.insetBy(dx: lineWidth,
dy: lineWidth), cornerRadius: cornerRadius).cgPath

用法:
let myView = View(frame: CGRect(x: 0, y: 0, width: 200, height: 50), cornerRadius: 25, colors: [UIColor.red, .orange, .yellow], lineWidth: 2, direction: .horizontal)
    myView.center = view.center
    view.addSubview(myView)

屏幕截图:

roundedViewWithGradient

09-10 00:35