How to fill a bezier path with gradient color

后端 未结 2 953
孤街浪徒
孤街浪徒 2020-12-30 07:29

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 anybod

2条回答
  •  死守一世寂寞
    2020-12-30 07:59

    To answer this question of yours,

    I have a UIBezierPath inside my custom UIView draw(_ rect: CGRect) function. I would like to fill the path with a gradient color.

    Lets say you have an oval path,

    let path = UIBezierPath(ovalIn: CGRect(x: 0, y: 0, width: 100, height: 100))
    

    To create a gradient,

    let gradient = CAGradientLayer()
    gradient.frame = path.bounds
    gradient.colors = [UIColor.magenta.cgColor, UIColor.cyan.cgColor]
    

    We need a mask layer for gradient,

    let shapeMask = CAShapeLayer()
    shapeMask.path = path.cgPath
    

    Now set this shapeLayer as mask of gradient layer and add it to view's layer as subLayer

    gradient.mask = shapeMask
    yourCustomView.layer.addSublayer(gradient)
    

    Update Create a base layer with stroke and add before creating gradient layer.

    let shape = CAShapeLayer()
    shape.path = path.cgPath
    shape.lineWidth = 2.0
    shape.strokeColor = UIColor.black.cgColor
    self.view.layer.addSublayer(shape)
    
    let gradient = CAGradientLayer()
    gradient.frame = path.bounds
    gradient.colors = [UIColor.magenta.cgColor, UIColor.cyan.cgColor]
    
    let shapeMask = CAShapeLayer()
    shapeMask.path = path.cgPath
    gradient.mask = shapeMask
    
    self.view.layer.addSublayer(gradient)
    

提交回复
热议问题