Search code examples
iosobjective-cuiimagecore-graphicsquartz-2d

Fill UIImage like a gauge using CG/Quartz


Lets say i have a an image (a semi-circle gauge) with colors starting from green to yellow to red. How can i programmatically clip and fill the image for a given percentage dynamically using CoreGraphics/Quartz ?


Solution

  • You can use a CALayer with a custom mask.

    The mask will be a CAShapeLayer with a path that defines the given percentage of the guage.

    CALayer *guageLayer = //your CALayer, could be the backing view
    
    CAShapeLayer *guageMask = [[CAShapeLayer alloc] init];
    guageMask.path = [self _pathForCurrentGuage]; //bezier path based on your current percentage
    
    guageLayer.mask = guageMask;