【问题标题】:Fill a CAShapeLayer with Gradient in swift?快速用渐变填充 CAShapeLayer?
【发布时间】:2017-11-26 21:06:46
【问题描述】:

我已经用 CAShapeLayer 填充了圆形边界。现在我将我的 CAShape 颜色设置为红色,但我想将其设置为渐变色。请告诉我该怎么做?

circlePath = UIBezierPath(arcCenter: centerPoint, radius: circleRadius, startAngle: CGFloat(1.5 * M_PI), endAngle: CGFloat(-0.5 * M_PI), clockwise: false)


        //add gradient to the below
        progressCircle = CAShapeLayer ()
        progressCircle.path = circlePath?.cgPath
        progressCircle.strokeColor = UIColor.red.cgColor
        progressCircle.fillColor = UIColor.clear.cgColor
        progressCircle.lineWidth = 4.0
        progressCircle.strokeStart = 0
        progressCircle.strokeEnd = 0.7

        let gradient: CAGradientLayer = CAGradientLayer()
        let startingColorOfGradient = UIColor(colorLiteralRed: 50/255, green: 189/255, blue: 170/255, alpha: 1.0).cgColor
        let endingColorOFGradient = UIColor(colorLiteralRed: 133/255, green: 210/255, blue: 230/255, alpha: 1.0).cgColor
        gradient.startPoint = CGPoint(x: 1.0, y: 0.5)
        gradient.endPoint = CGPoint(x: 0.0, y: 0.5)
        gradient.colors = [startingColorOfGradient , endingColorOFGradient]

        circle.layer.addSublayer(progressCircle)
circle.layer.addSublayer(gradient)

【问题讨论】:

标签: ios swift xcode cashapelayer


【解决方案1】:

我认为您缺少渐变框架、渐变位置,您应该将其添加到图层的蒙版中。以下示例适用于我:

let gradient = CAGradientLayer()
gradient.startPoint = CGPoint(x: 1, y: 0.5)
gradient.endPoint = CGPoint(x: 0, y: 0.5)
gradient.frame = CGRect(x: 0, y: 0, width: yourWidth, height: yourHeight)
gradient.colors = [
    UIColor(white: 1, alpha: 0.1).cgColor,
    UIColor(white: 1, alpha: 0.5).cgColor,
    UIColor(white: 1, alpha: 0.9).cgColor
]
gradient.locations = [
    0.0,
    0.5,
    1.0
]
circle.layer.mask = gradient

希望这会有所帮助!

【讨论】:

  • 如果我使用我的颜色作为红绿色,那么它不会显示任何效果。我提供了框架但它只显示红色
猜你喜欢
  • 1970-01-01
  • 2021-12-05
  • 1970-01-01
  • 2011-06-11
  • 2011-08-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-02
相关资源
最近更新 更多