如何用drawRect中的渐变填充path:?

用纯色填充path很简单:

CGPoint aPoint; for (id pointValue in points) { aPoint = [pointValue CGPointValue]; CGContextAddLineToPoint(context, aPoint.x, aPoint.y); } [[UIColor redColor] setFill]; [[UIColor blackColor] setStroke]; CGContextDrawPath(context, kCGPathFillStroke); 

我想绘制一个渐变而不是纯红的,但我有麻烦。 我已经尝试了在UIView和UILabels在iPhone上的问题/答案: 渐变中列出的代码

这是:

 CAGradientLayer *gradient = [CAGradientLayer layer]; [gradient setFrame:rect]; [gradient setColors:[NSArray arrayWithObjects:(id)[[UIColor blueColor] CGColor], (id)[[UIColor whiteColor] CGColor], nil]]; [[self layer] setMasksToBounds:YES]; [[self layer] insertSublayer:gradient atIndex:0]; 

然而,这就描绘了这个渐变的整体观点,掩盖了我原来的路线。

我会剪裁到你想要填充的path,并使用CGContextDrawLinearGradient。 下面是一个简单的drawRect实现:作为一个例子:

 - (void) drawRect:(CGRect)rect { // Create a gradient from white to red CGFloat colors [] = { 1.0, 1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 1.0 }; CGColorSpaceRef baseSpace = CGColorSpaceCreateDeviceRGB(); CGGradientRef gradient = CGGradientCreateWithColorComponents(baseSpace, colors, NULL, 2); CGColorSpaceRelease(baseSpace), baseSpace = NULL; CGContextRef context = UIGraphicsGetCurrentContext(); CGContextSaveGState(context); CGContextAddEllipseInRect(context, rect); CGContextClip(context); CGPoint startPoint = CGPointMake(CGRectGetMidX(rect), CGRectGetMinY(rect)); CGPoint endPoint = CGPointMake(CGRectGetMidX(rect), CGRectGetMaxY(rect)); CGContextDrawLinearGradient(context, gradient, startPoint, endPoint, 0); CGGradientRelease(gradient), gradient = NULL; CGContextRestoreGState(context); CGContextAddEllipseInRect(context, rect); CGContextDrawPath(context, kCGPathStroke); } 
Interesting Posts