How to make a fade effect using Core Graphics?

I want to make an effect similar to what you see on the right side of the first cell:

enter image description here

I suppose this is some kind of overlay with a gradient, but I just can't figure out how it is configured with transparency. I tried to create my own overlay view with a gradient and set the alpha of the colors down, but it just displays as a gray-white gradient.

CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    CGContextRef context = UIGraphicsGetCurrentContext();

    UIColor *gradBegin = [UIColor colorWithWhite:1.0 alpha:0.8];
    UIColor *gradEnd = [UIColor colorWithWhite:1.0 alpha:0.6];
    NSArray* gradientColors = [NSArray arrayWithObjects: 
                               (id)gradBegin.CGColor, 
                               (id)gradEnd.CGColor, nil];
    CGFloat gradientLocations[] = {0, 1};

    CGGradientRef gradient = CGGradientCreateWithColors(colorSpace, (__bridge CFArrayRef)gradientColors, gradientLocations);

    CGContextDrawLinearGradient(context, gradient, CGPointMake(rect.origin.x, rect.origin.y + rect.size.height/2.0), 
                                CGPointMake(rect.origin.x + rect.size.width, rect.origin.y + rect.size.height/2.0), 0);

What exactly is happening in this screenshot and how can I reproduce it?

+3
source share
3 answers

I wrote a simple UIView class that will draw on its own. This is the main UIView with overriding drawRect:

- (void)drawRect:(CGRect)rect
{
    CGColorSpaceRef colourSpace = CGColorSpaceCreateDeviceRGB();
    CGContextRef context = UIGraphicsGetCurrentContext();

    UIColor* gradBegin = [UIColor colorWithWhite:1 alpha:0];
    UIColor* gradEnd = [UIColor colorWithWhite:1 alpha:1];
    NSArray* gradColours = [NSArray arrayWithObjects:
                                    (id)gradBegin.CGColor,
                                    (id)gradBegin.CGColor,
                                    (id)gradEnd.CGColor,
                                    (id)gradEnd.CGColor, nil];
    CGFloat gradLocs[] = { 0, 0.5, 0.9, 1 };
    CGGradientRef gradient = CGGradientCreateWithColors(colourSpace, (__bridge CFArrayRef)gradColours, gradLocs);
    CGContextDrawLinearGradient(context, gradient, CGPointMake(0, 0), CGPointMake(self.frame.size.width, 0), 0);
    CGGradientRelease(gradient);
    CGColorSpaceRelease(colourSpace);
}

This works if it overlays your view and the background of the view is white.

+2
source

Core Graphics, PNG 1 , UIImageView .

+2

The gradient drawing code in your question looks fine, although I have not tested it. I suggest installing gradBegin.alpha = 0and gradEnd.alpha = 1. In addition, the last line can be simplified:

CGContextDrawLinearGradient(context, gradient, rect.origin,
    CGPointMake(CGRectGetMaxX(rect), rect.origin.y, 0);

And do not forget CGGradientRelease(gradient).

In any case, apart from this, you need to install overlayView.opaque = NO.

+1
source

All Articles