Search code examples
iosobjective-cgradientlayer

Drawing gradient over image in ios


How to create gradient colour look like following image programatically.

enter image description here


Solution

  • When you say "apply it over the image as a gradient", do you mean as a mask (revealing the image at the top, having it fade the image to transparent at the bottom)? If that's the case, you can apply that gradient as a mask, using CAGradientLayer:

    CAGradientLayer *gradientMask = [CAGradientLayer layer];
    gradientMask.frame = self.imageView.bounds;
    gradientMask.colors = @[(id)[UIColor whiteColor].CGColor,
                            (id)[UIColor clearColor].CGColor];
    self.imageView.layer.mask = gradientMask;
    

    The above does a simple vertical gradient (because the default is vertical, linear gradient). But you asked about startPoint, endPoint, and locations. If for example, you wanted your mask applied horizontally, you would do:

    gradientMask.startPoint = CGPointMake(0.0, 0.5);   // start at left middle
    gradientMask.endPoint = CGPointMake(1.0, 0.5);     // end at right middle
    

    If you wanted to have two gradients, one at the first 10% and another at the last 10%, you'd do:

    gradientMask.colors = @[(id)[UIColor clearColor].CGColor,
                            (id)[UIColor whiteColor].CGColor,
                            (id)[UIColor whiteColor].CGColor,
                            (id)[UIColor clearColor].CGColor];
    gradientMask.locations = @[@0.0, @0.10, @0.90, @1.0];
    

    If you want a simple gradient by itself (not as a mask), you'd create a view and then add the gradient layer to it:

    CAGradientLayer *gradient = [CAGradientLayer layer];
    gradient.frame = view.bounds;
    gradient.colors = @[(id)[UIColor whiteColor].CGColor,
                        (id)[UIColor blackColor].CGColor];
    [view.layer addSublayer:gradient];
    

    See the CAGradientLayer class reference.