开发者

Linear gradient aliasing with CoreGraphics

I'm trying to emulate the color tint effect from the UITabBarItem.

When I draw a linear gradient at an angle, I get visible aliasing in the middle part of the gradient where the two colors meet at the same location. Left is UITabBarItem, right is my gradient with visible aliasing (stepping):

Linear gradient aliasing with CoreGraphics

Here is the snippet of relevant code:

UIGraphicsBeginImageContextWithOptions(size, NO, 0.0);
CGContextRef c = UIGraphicsGetCurrentContext();

CGContextSaveGState(c);
CGContextScaleCTM(c, 1.0, -1.0);

CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();  
CGFloat components[16] = {1,1,1,1, 
                          109.0/255.0,175.0/255.0,246.0/255.0,1, 
                          31.0/255.0,133.0/255.0,242.0/255.0,1, 
                          143.0/255.0,194.0/255.0,248.0/255.0,1};
CGFloat locations[4] = {0.0, 0.62, 0.62, 1};
CGGradientRef colorGradient = 
      CGGradientCreateWithColorComponents(colorSpace, components, 
                                          locations, (size_t)4);
CGContextDrawLinearGradient(c, colorGradient, CGPointZero,
 开发者_高级运维                           CGPointMake(size.width*1.0/3.9, -size.height),0);
CGGradientRelease(colorGradient);
CGColorSpaceRelease(colorSpace);
CGContextRestoreGState(c);

UIImage *resultImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

return resultImage;

What do I need to change, to get a smooth angled gradient like in UITabBarItem?


What is the interpolation quality of your context set to? CGContextGetInterpolationQuality()/CGContextSetInterpolationQuality(). Try changing that if it's too low.

If that doesn't work, I'm curious what happens if you draw the gradient vertically (0,Ymin)-(0,Ymax) but apply a rotation transformation to your context...


As a current workaround, I draw the gradient at double resolution into an image and then draw the image with original dimensions. The image scaling that occurs, takes care of the aliasing. At the pixel level the result is not as smooth as in the UITabBarItem, but that probably uses an image created in Photoshop or something similar.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜