I have a UIBezierPath
inside my custom UIView draw(_ rect: CGRect)
function. I would like to fill the path with a gradient color. Please can anybody guide me how can I do that.
I need to fill the clip with a gradient color and then stroke the path with black color.
There are some posts in SO which does not solve the problem. For example Swift: Gradient along a bezier path (using CALayers) this post guides how to draw on a layer in UIView
but not in a UIBezierPath
.
NB: I am working on Swift-3
You can do this directly in Core Graphics without using
CALayer
classes. UsebezierPath.addClip()
to set the bezier path as the clipping region. Any subsequent drawing commands will be masked to that region.I use this wrapper function in one of my projects:
To answer this question of yours,
Lets say you have an oval path,
To create a gradient,
We need a mask layer for gradient,
Now set this
shapeLayer
asmask
ofgradient
layer and add it toview
's layer assubLayer
Update Create a base layer with stroke and add before creating gradient layer.