Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CAGradientLayer not smooth enough?

I'm doing a CAGradientLayer for every background of my UIViews, but I have a small problem. The gradient doesn't seem that smooth enough. The transition between the colors are to present. You can see it in this picture.

Wrong gradient screenshot

This is how I implemented this gradient in the initializer of my UIView.

CAGradientLayer *layer = [CAGradientLayer layer];
layer.colors = [NSArray arrayWithObjects:
                (id)[[UIColor darkKinepolisColor] CGColor],
                (id)[[UIColor lightKinepolisColor] CGColor],
                (id)[[UIColor lightKinepolisColor] CGColor],
                (id)[[UIColor darkKinepolisColor] CGColor],
                nil];
layer.locations = [NSArray arrayWithObjects:
                   [NSNumber numberWithFloat:0],
                   [NSNumber numberWithFloat:0.4],
                   [NSNumber numberWithFloat:0.6],
                   [NSNumber numberWithFloat:1],
                   nil];
layer.startPoint = CGPointMake(0, 0);
layer.frame = self.layer.bounds;
layer.endPoint = CGPointMake(1, 1);
layer.contentsGravity = kCAGravityResize;
[self.layer addSublayer:layer];

Could you, fine developers, help me with this problem? Thanks!

like image 467
Dries De Smet Avatar asked Sep 26 '11 12:09

Dries De Smet


2 Answers

From what I've seen CAGradientLayer does not support dithering, but CGGradient does. See my answer here. Also see the other answers for example on using CGGradient.

like image 172
ThomasW Avatar answered Sep 30 '22 02:09

ThomasW


Isn't this just a consequence of 8-bit colour values? The steps between the colours are as small as they can possibly be.

i.e. if you want a gradient between rgb(100,100,100) and rgb(109,109,109) it can only be perfectly smooth across a gradient width of 10 pixels. If you tried to draw this gradient across a width of 100 pixels you would get 10 blocks of colour 10px wide and it would look very blocky. What else could happen?

You can make it appear smoother by dithering and adding noise but there is no built in function for this.

So, either, choose colours farther apart, draw the gradient over a shorter distance or make the graphic in Photoshop and apply noise and dithering to make it appear smoother.

like image 34
hooleyhoop Avatar answered Sep 30 '22 02:09

hooleyhoop