Fork me on GitHub

关于ios颜色渐进的总结

最近一直在做iphone自定义控件,对于ios上面的图形控制和一些api也有了些认识,所以总结一些。

颜色渐进是做图像的基本东西,要想做的漂亮,肯定必不可少。

用到的基本api是 CGGradientRef.

/**

画图形渐进色方法,此方法只支持双色值渐变
@param context 图形上下文的CGContextRef
@param clipRect 需要画颜色的rect
@param startPoint 画颜色的起始点坐标
@param endPoint 画颜色的结束点坐标
@param options CGGradientDrawingOptions
@param startColor 开始的颜色值
@param endColor 结束的颜色值
*/
- (void)DrawGradientColor:(CGContextRef)context
rect:(CGRect)clipRect
point:(CGPoint) startPoint
point:(CGPoint) endPoint
options:(CGGradientDrawingOptions) options
startColor:(UIColor*)startColor
endColor:(UIColor*)endColor
{
UIColor* colors [2] = {startColor,endColor};
CGColorSpaceRef rgb = CGColorSpaceCreateDeviceRGB();
CGFloat colorComponents[8];

for (int i = 0; i < 2; i++) {
UIColor *color = colors[i];
CGColorRef temcolorRef = color.CGColor;

const CGFloat *components = CGColorGetComponents(temcolorRef);
for (int j = 0; j < 4; j++) {
colorComponents[i * 4 + j] = components[j];
}
}

CGGradientRef gradient = CGGradientCreateWithColorComponents(rgb, colorComponents, NULL, 2);

CGColorSpaceRelease(rgb);
CGContextDrawLinearGradient(context, gradient, startPoint, endPoint, options);
CGGradientRelease(gradient);
}

 

这样的方法可是实现颜色的渐变,但是这只是双色渐变,如果想多色渐变的话,那就生成UIColor* 数组到响应的数目,同时在遍历color生成CGColorRef 的时候,用数组长度的item下标把颜色一一取出来即可。
同时,在这里我们画颜色渐进的宽度,需要用到clipRect. 这个rect  大小是需要定义的,并且我们需要把context 给前切成这个rect的大小。

比如我们当前的 context是对于整个屏幕的,我们需要在中间截取一个rect,则先保持住现在的context.  

CGContextSaveGState(context);

然后我们截取对应的context

CGContextClipToRect(context, clipRect); 
......
......

用完这个context之后,我们还要恢复到之前的context

CGContextRestoreGState(context);

至此,就完成了。我实现的是在屏幕里画一个矩形,然后在矩形里,实现渐进色的功能,大家可以尝试一下。





posted on 2012-03-03 23:24  pengyingh  阅读(5267)  评论(0编辑  收藏  举报

导航