关于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 阅读(5276) 评论(0) 编辑 收藏 举报
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步