2

hi i have a circle shapeLayer need color by GradientColor

i tried ues CAGradientLayer and mask it like this

let gradientChargeLayer = CAGradientLayer()
    gradientChargeLayer.colors = CGColor.mColor
    gradientChargeLayer.frame = vShape.bounds
    gradientChargeLayer.locations = [0,1]
    gradientChargeLayer.startPoint = CGPoint(x: 0,y: 0.5)
    gradientChargeLayer.endPoint = CGPoint(x: 1,y: 0.5)
    gradientChargeLayer.mask = shapeLayer
    vShape.layer.addSublayer(gradientChargeLayer)

enter image description here

but what i want is gradient color from stroke start to end

    shapeLayer.path = circularPath.cgPath
    shapeLayer.strokeColor = UIColor.red.cgColor   <<< here 

thanks

saint
  • 103
  • 11

2 Answers2

0

you could’ve different approaches I believe

  • One, you could make an outer and inner circle and then add the required path/layer to the outer circle (this circle bigger than inner) both circles without visible stroke

  • Or I could recommend you UIGraphigsImageRenderer to work with https://developer.apple.com/documentation/uikit/uigraphicsimagerenderer This last have a context that could be used to do more advanced rendering context.cgContext.setStrokePattern here you can add a CGPattern and colors to trying accomplish it

PD. Sorry if my english is confuse

Guillodacosta
  • 383
  • 3
  • 8
0

Shape layers only draw in a single color, as I guess you are aware.

By making your shape layer a mask onto a gradient layer you're able to have the shape layer reveal the color of the underlying gradient layer.

If you are always drawing a circle and want the color of the circle's stroke to vary from beginning to end you could set up your gradient layer using a type of conic, and specifying the colors in the gradient layer to begin and end where you want them. However, that would only work for shape layers that contain ovals, where the size and center of the shape and the size and the center of the gradient match.

As @Guillodacosta said in their answer, you may have to give up on using a shape layer and draw your graphic into a graphics context using Core Graphics. (You could do that once and capture the results into a UIImageView to avoid the slowdown of Core Graphics rendering.)

Duncan C
  • 128,072
  • 22
  • 173
  • 272