sfeuerstein
sfeuerstein

Reputation: 913

Can't get CGGradientRef to work with alpha

I am trying to apply an alpha gradient to a UIView but can't get it to work at all. My current drawRect: method looks like this -

- (void)drawRect:(CGRect)rect
{
    CGContextRef currentContext = UIGraphicsGetCurrentContext();

    CGGradientRef alphaGradient;
    CGColorSpaceRef rgbColorSpace;
    size_t num_locations = 2;
    CGFloat locations[2] = { 0.0, 1.0 };
    CGFloat components[8] = { 1.0, 1.0, 1.0, 1.0,  // Start color
    1.0, 1.0, 1.0, 0.0 }; // End color

    rgbColorSpace = CGColorSpaceCreateDeviceRGB();
    alphaGradient = CGGradientCreateWithColorComponents(rgbColorSpace, components, locations, num_locations);

    CGRect currentBounds = self.bounds;
    CGPoint bottomCenter = CGPointMake(CGRectGetMidX(currentBounds), CGRectGetMaxY(currentBounds));
    CGPoint midCenter = CGPointMake(CGRectGetMidX(currentBounds), CGRectGetMidY(currentBounds));
    CGContextDrawLinearGradient(currentContext, alphaGradient, midCenter, bottomCenter, 0);

    CGGradientRelease(alphaGradient);
    CGColorSpaceRelease(rgbColorSpace);
}

I am sure there is something I am missing here. I have tried changing the RGB values to 0.0 instead of 1.0, changing the color space to gray scale, etc.

Any help pointing me in the right direction would be much appreciated. Thanks

Upvotes: 0

Views: 496

Answers (2)

sfeuerstein
sfeuerstein

Reputation: 913

I resolved the issue by making sure the view's background color was set to clear, then applying the view's layer as a mask on the image view.

Upvotes: 2

Logan
Logan

Reputation: 53112

I use CAGradient:

UIView * viewToGradient = // view to add gradient
UIColor * color1 = [UIColor lightGrayColor]; // gradient color 1
UIColor * color2 = [UIColor clearColor]; // gradient color 2

CAGradientLayer * gradientLayer = [CAGradientLayer layer];
gradientLayer.frame = viewToGradient.bounds;
gradientLayer.colors = [NSArray arrayWithObjects:(id)color1.CGColor, (id)color2.CGColor, nil];
gradientLayer.opacity = .6;
[viewToGradient.layer addSublayer:gradientLayer];

Upvotes: 0

Related Questions