CALayer mask - combining two layers

In my app i have a view and i want it to have a small transparent gradients on left and right side. I am able to create either left or right gradient pretty easily, but i dont know how to combine them :

CAGradientLayer *rightLayer = [CAGradientLayer layer];
rightLayer.frame = self.bounds;
rightLayer.colors = [NSArray arrayWithObjects:(id)[UIColor whiteColor].CGColor, (id)[UIColor clearColor].CGColor, nil];
rightLayer.startPoint = CGPointMake(0.8f, 1.0f);
rightLayer.endPoint = CGPointMake(1.0f, 1.0f);

CAGradientLayer *leftLayer = [CAGradientLayer layer];
leftLayer.frame = self.bounds;
leftLayer.colors = [NSArray arrayWithObjects:(id)[UIColor clearColor].CGColor,(id)[UIColor whiteColor].CGColor, nil];
leftLayer.startPoint = CGPointMake(0.0f, 1.0f);
leftLayer.endPoint = CGPointMake(0.2f, 1.0f);


self.layer.mask = leftLayer;

As you can see, the problem is that i must assign only 1 layer to mask and i want it to have 2 layers. How do i merge leftLayer and rightLayer? Or how do i add both of these layers to mask?

Thanks a lot for answering!

Answers


You will have to create one gradient layer with a gradient that goes from clear to white to clear again and set the locations for the three points. So you will have to set the endPoint to be at the other side of your view (cover the entire width) by setting it to 1.

You need to wrap your points in NSValue objects to add them to the locations array, like this: [NSValue valueWithCGPoint:myCGPoint];

Since the locations are defined between 0 and 1. You will have to calculate the values depending on the width of the layer you are masking. Something like this:

0.2/width         // left edge
(width-0.2)/width // right edge

You are already setting the start and end point in the range of 0 to 1 so just use the same values.


The trick is to use "locations" as mentioned by the others. The code below does a "fade out" gradient in the top and the bottom -- useful if you want to have scrolling text fade out of your screen in both ends. The location stops below should be read as 0.0 => 0.1 is fade from clear to white and then 0.9 => 1.0 is fade from white to clear again.

CAGradientLayer *gradient = [CAGradientLayer layer];
gradient.frame = self.bounds;
gradient.colors = @[(id)[[UIColor clearColor] CGColor], (id)[[UIColor whiteColor] CGColor], (id)[[UIColor whiteColor] CGColor], (id)[[UIColor clearColor] CGColor]];
gradient.startPoint = CGPointMake(0.5, 0.0);
gradient.endPoint = CGPointMake(0.5, 1.0);
gradient.locations = @[@0.0, @0.1, @0.9, @1.0];

[self.layer setMask:gradient];

Remember to include #import <QuartzCore/QuartzCore.h> in your file.


Need Your Help

Jquery toggling each and every div with same id

jquery layout html toggle

I want to toggle a bunch of divs that each have the same id.