Search code examples
swiftuiscrollviewslideruibezierpathcurve

iOS Fill half of UIBezierPath with other color without CAGradientLayer


I have a question about drawing half of a UIBezierPath. How do I fill left part (left from thumb) with green color and right part (right from thumb) with white color without using CAGradientLayer?

Code I used to create Bezier Path - https://gist.github.com/robertmryan/67484c74297cede3926a3aed2fceedb9

Screenshot of what I want to achieve:

enter image description here


Solution

  • One approach is to add a mask layer to your curved-path shape layer.

    When the "thumb" position changes, change the width of the mask to reveal only the "left-side" of the shape layer.

    Create a shape layer to use as the mask:

    let maskLayer: CALayer = {
        let layer = CALayer()
        layer.backgroundColor = UIColor.black.cgColor
        return layer
    }()
    

    In viewDidLoad() set that layer as the mask for the curved-shape layer:

    pathLayer.mask = maskLayer
    

    Whenever the "thumb" position is set, update the width of the mask:

    func updateMask(at point: CGPoint) -> Void {
        var f = view.bounds
        f.size.width = point.x
        CATransaction.begin()
        CATransaction.setDisableActions(true)
        maskLayer.frame = f
        CATransaction.commit()
    }
    

    I posted a modified version of your gist at: https://gist.github.com/DonMag/a2154e70a3c67193a7b19bee41c8fe95

    It really has only a few changes... look for comments beginning with // DonMag -

    Here is the result (with an imageView behind it to show the transparency):

    enter image description here


    Edit

    After comments, the goal is to have the "right-side" of the track path be white instead of transparent.

    Using the same approach, we can add a white shape layer on top of the original shape layer, and mask it to show only the right-hand-side.

    Here is an updated gist - https://gist.github.com/DonMag/397dfbe4779e817531ef7a663365b2e7 - showing this result:

    enter image description here