在iOS Core Graphics中繪制漸變顏色主要是通過(guò)使用CGContextDraw(xxx)Gradient相關(guān)函數(shù)农尖,比如募强,常見(jiàn)的線(xiàn)性漸變就是CGContextDrawLinearGradient函數(shù)懦傍,這里帖子封裝了繪制漸變顏色的具體代碼過(guò)程,我們拿過(guò)來(lái)直接用答渔,只不過(guò)原帖代碼是用CGContextAddRect畫(huà)了一個(gè)矩形灌侣,我們改一下去畫(huà)CGPathRef。這里無(wú)論是什么形狀其實(shí)無(wú)所謂卖陵,原理都是用來(lái)做Clip遭顶,所以需要在CGContextClip函數(shù)前調(diào)用CGContextAddPath函數(shù)把CGPathRef加入到Context中。
另外一個(gè)需要注意的地方是漸變的方向泪蔫,方向是由兩個(gè)點(diǎn)控制的棒旗,點(diǎn)的單位就是坐標(biāo)。因此需要正確從CGPathRef中找到正確的點(diǎn)撩荣,方法當(dāng)然有很多種看具體實(shí)現(xiàn)嗦哆,本例中,我就是簡(jiǎn)單得通過(guò)調(diào)用CGPathGetBoundingBox函數(shù)婿滓,返回CGPathRef的矩形區(qū)域老速,然后根據(jù)這個(gè)矩形取兩個(gè)點(diǎn),讀者可以根據(jù)自行需求修改具體代碼凸主。
OK橘券,把代碼封裝成一個(gè)方法,類(lèi)似這樣:
/**
* 修改自http://www.raywenderlich.com/32283/core-graphics-tutorial-lines-rectangles-and-gradients
*/
- (void)drawLinearGradient:(CGContextRef)context
path:(CGPathRef)path
startColor:(CGColorRef)startColor
endColor:(CGColorRef)endColor
{
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGFloat locations[] = { 0.0, 1.0 };
NSArray *colors = @[(__bridge id) startColor, (__bridge id) endColor];
CGGradientRef gradient = CGGradientCreateWithColors(colorSpace, (__bridge CFArrayRef) colors, locations);
CGRect pathRect = CGPathGetBoundingBox(path);
//具體方向可根據(jù)需求修改
CGPoint startPoint = CGPointMake(CGRectGetMidX(pathRect), CGRectGetMinY(pathRect));
CGPoint endPoint = CGPointMake(CGRectGetMidX(pathRect), CGRectGetMaxY(pathRect));
CGContextSaveGState(context);
CGContextAddPath(context, path);
CGContextClip(context);
CGContextDrawLinearGradient(context, gradient, startPoint, endPoint, 0);
CGContextRestoreGState(context);
CGGradientRelease(gradient);
CGColorSpaceRelease(colorSpace);
}
接下來(lái)就可以使用了卿吐,示例代碼:
- (void)viewDidLoad {
[super viewDidLoad];
//創(chuàng)建CGContextRef
UIGraphicsBeginImageContext(self.view.bounds.size);
CGContextRef gc = UIGraphicsGetCurrentContext();
//創(chuàng)建CGMutablePathRef
CGMutablePathRef path = CGPathCreateMutable();
//繪制Path
CGRect rect = CGRectInset(self.view.bounds, 30, 30);
CGPathMoveToPoint(path, NULL, CGRectGetMinX(rect), CGRectGetMinY(rect));
CGPathAddLineToPoint(path, NULL, CGRectGetMidX(rect), CGRectGetHeight(rect));
CGPathAddLineToPoint(path, NULL, CGRectGetWidth(rect), CGRectGetHeight(rect) * 2 / 3);
CGPathCloseSubpath(path);
//繪制漸變
[self drawLinearGradient:gc path:path startColor:[UIColor greenColor].CGColor endColor:[UIColor redColor].CGColor];
//注意釋放CGMutablePathRef
CGPathRelease(path);
//從Context中獲取圖像旁舰,并顯示在界面上
UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
UIImageView *imgView = [[UIImageView alloc] initWithImage:img];
[self.view addSubview:imgView];
}