【问题标题】:Rounded Gradient Border on UIButtonUIButton 上的圆形渐变边框
【发布时间】:2018-05-28 02:44:21
【问题描述】:

您好,我一直在尝试在我的应用程序中实现一个 UIButton,它具有圆角和渐变边框。我使用以下代码在我的按钮上创建了渐变边框:

    let gradient = CAGradientLayer()
    gradient.frame =  CGRect(origin: CGPoint.zero, size: self.myBtn.frame.size)
    gradient.colors = [colourOne.cgColor, colourTwo.cgColor]

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

    self.myBtn.layer.addSublayer(gradient)

这段代码可以很好地创建边框,但从图片中可以看出,边角没有正确圆角。我尝试过的其他技术使圆角完全不可见。

另外,我需要按钮是透明填充,所以我不能简单地做一个渐变填充。

如果有人能帮我解释一下,将不胜感激。

【问题讨论】:

    标签: ios swift uibutton gradient


    【解决方案1】:

    您需要在使用UIButton boundscornerRadius 创建UIBezierPath 之前设置圆角半径。

    试试下面:

    self.myBtn.layer.cornerRadius = self.myBtn.frame.height/2
    self.myBtn.clipsToBounds = true
    
    let gradient = CAGradientLayer()
    gradient.frame =  CGRect(origin: CGPoint.zero, size: self.myBtn.frame.size)
    gradient.colors =  [UIColor.blue.cgColor, UIColor.green.cgColor]
    
    let shape = CAShapeLayer()
    shape.lineWidth = 6
    
    shape.path = UIBezierPath(roundedRect: self.myBtn.bounds, cornerRadius: self.myBtn.layer.cornerRadius).cgPath
    
    shape.strokeColor = UIColor.black.cgColor
    shape.fillColor = UIColor.clear.cgColor
    gradient.mask = shape
    
    self.myBtn.layer.addSublayer(gradient)
    

    输出:-

    【讨论】:

    • 如何给渐变边框添加阴影
    猜你喜欢
    • 2019-03-03
    • 2018-02-12
    • 1970-01-01
    • 1970-01-01
    • 2018-02-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-03
    相关资源
    最近更新 更多