Search code examples
iosios7maskcagradientlayer

layer.mask gradient is Solid in iOS7


The next code was working fine in ios6. It is supposed to apply a top and bottom inner alpha gradient to a view:

CAGradientLayer * gradient = [CAGradientLayer layer];
gradient.frame = self.bounds;
gradient.colors = [NSArray arrayWithObjects:(id)[[UIColor clearColor] CGColor],
                   (id)[[UIColor whiteColor]CGColor],
                   (id)[[UIColor whiteColor]CGColor],
                   (id)[[UIColor clearColor] CGColor],
                   nil];

gradient.startPoint = CGPointMake(0.5, 0.0);
gradient.endPoint = CGPointMake(0.5, 1.0);
gradient.locations = [NSArray arrayWithObjects:@0,@(val),@(1.-val),@1,nil];

self.layer.mask = gradient;

BUT! If I run this code in iOS7, instead of a nice blending alpha gradient the "transparent" parts of the gradient are solid white.


Solution

  • I would put this in comments, but the formatting would be off. This snippet of code works for me in iOS 7. You can adapt it to your needs. If it's still not working then I would say that the gradient is not the problem.

    +(void)addScrollingGradientToView:(UIView*)view
    {
        //add in the gradient to show scrolling
        CAGradientLayer *nextImageFade = [CAGradientLayer layer];
        nextImageFade.frame = CGRectInset(view.bounds,-10,-10);
    
        nextImageFade.colors = [NSArray arrayWithObjects:(id)[UIColor colorWithRed:0. green:0. blue:0. alpha:0.].CGColor,
                                [UIColor colorWithRed:0. green:0. blue:0. alpha:1.0].CGColor,
                                [UIColor colorWithRed:0. green:0. blue:0. alpha:1.0].CGColor,
                                [UIColor colorWithRed:0. green:0. blue:0. alpha:0.0].CGColor,nil];
        nextImageFade.locations = [NSArray arrayWithObjects:[NSNumber numberWithFloat:0.0],
                                   [NSNumber numberWithFloat:20 / view.frame.size.height],
                                   [NSNumber numberWithFloat:(view.frame.size.height - 20) / view.frame.size.height],
                                   [NSNumber numberWithFloat:1.], nil];
        nextImageFade.startPoint = CGPointMake(.5, 0);
        nextImageFade.endPoint = CGPointMake(.5, 1);
    
        //Put in the fading last so that it is above everything else
        [view.layer setMask:nextImageFade];
    }