您好,登錄后才能下訂單哦!
兩段代碼,首先是使用方法
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進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。