两段代码,首先是使用方法
CGContextRef context = UIGraphicsGetCurrentContext(); NSArray *colors = [NSArray arrayWithObjects: [UIColor colorWithRed:225.0 / 255.0 green:225.0 / 255.0 blue:225.0 / 255.0 alpha:1.0], [UIColor colorWithRed:168.0 / 255.0 green:168.0 / 255.0 blue:168.0 / 255.0 alpha:1.0], nil]; [self _drawGradientColor:context rect:CGRectMake(rX, rY, rW, rH) options:kCGGradientDrawsAfterEndLocation colors:colors]; CGContextStrokePath(context);// 描线,即绘制形状 CGContextFillPath(context);// 填充形状内的颜色
在一段就是绘制背景色渐变的矩形
/** * 绘制背景色渐变的矩形,p_colors渐变颜色设置,集合中存储UIColor对象(创建Color时一定用三原色来创建) **/ - (void)_drawGradientColor:(CGContextRef)p_context rect:(CGRect)p_clipRect options:(CGGradientDrawingOptions)p_options colors:(NSArray *)p_colors { CGContextSaveGState(p_context);// 保持住现在的context CGContextClipToRect(p_context, p_clipRect);// 截取对应的context int colorCount = p_colors.count; int numOfComponents = 4; CGColorSpaceRef rgb = CGColorSpaceCreateDeviceRGB(); CGFloat colorComponents[colorCount * numOfComponents]; for (int i = 0; i < colorCount; i++) { UIColor *color = p_colors[i]; CGColorRef temcolorRef = color.CGColor; const CGFloat *components = CGColorGetComponents(temcolorRef); for (int j = 0; j < numOfComponents; ++j) { colorComponents[i * numOfComponents + j] = components[j]; } } CGGradientRef gradient = CGGradientCreateWithColorComponents(rgb, colorComponents, NULL, colorCount); CGColorSpaceRelease(rgb); CGPoint startPoint = p_clipRect.origin; CGPoint endPoint = CGPointMake(CGRectGetMinX(p_clipRect), CGRectGetMaxY(p_clipRect)); CGContextDrawLinearGradient(p_context, gradient, startPoint, endPoint, p_options); CGGradientRelease(gradient); CGContextRestoreGState(p_context);// 恢复到之前的context }
还有一种实现方式
CAGradientLayer *gradient = [CAGradientLayer layer]; gradient.frame = CGRectMake(rX, rY, rW, rH); gradient.colors = [NSArray arrayWithObjects: (id)[UIColor blackColor].CGColor, (id)[UIColor grayColor].CGColor, (id)[UIColor blackColor].CGColor, nil]; [self.view.layer insertSublayer:gradient atIndex:0];
记得要
#import <QuartzCore/QuartzCore.h>
此文的完成用到了四位老师的文章,在此表示感谢。
http://www.cnblogs.com/pengyingh/articles/2378840.html
http://www.dapps.net/dev/code/ios-dev-cgcontext-tips.html
http://www.cnblogs.com/smileEvday/archive/2012/06/05/UIColor_CIColor_CGColor.html
http://blog.csdn.net/reylen/article/details/8622932
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。