Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
427 views
in Technique[技术] by (71.8m points)

objective c - Drawing gradient over image in ios

How to create gradient colour look like following image programatically.

enter image description here

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...