Ios 如何绘制渐变填充弧,即彩虹?

Ios 如何绘制渐变填充弧,即彩虹?,ios,iphone,objective-c,Ios,Iphone,Objective C,下面的代码绘制了一个从红色到绿色渐变的半圆。 这不是我想要的。 我希望有一个宽度为5像素的弧,并用渐变绘制 如果有人能帮我指出哪里出了问题,我将不胜感激 查尔斯 -(void) DrawRainbow { // Create an arc path float x = 150.0; float y = 220.0; float radius = 75.0; float startAngle = M_PI; float endAngle = 2*M_PI; bool clockWise = f

下面的代码绘制了一个从红色到绿色渐变的半圆。 这不是我想要的。 我希望有一个宽度为5像素的弧,并用渐变绘制

如果有人能帮我指出哪里出了问题,我将不胜感激

查尔斯

-(void) DrawRainbow {
// Create an arc path
float x = 150.0;
float y = 220.0;
float radius = 75.0;
float startAngle = M_PI;
float endAngle   = 2*M_PI;
bool clockWise = false;
CGMutablePathRef path = CGPathCreateMutable();
CGPathAddArc(path, nil, x, y, radius, startAngle, endAngle, clockWise);

// Setup the gradient
size_t num_locations = 2;
CGFloat locations[2] = { 0.0, 1.0 };
CGFloat components[8] = {
    1.0, 0.0, 0.0, 1.0,   // Start color is red
    0.0, 1.0, 0.0, 1.0 }; // End color is green
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGGradientRef gradientFill = 
    CGGradientCreateWithColorComponents (colorSpace, components,
                                         locations, num_locations);
// setup gradient points
CGRect pathRect = CGPathGetBoundingBox(path);
CGPoint myStartPoint, myEndPoint;
myStartPoint.x = CGRectGetMinX(pathRect);
myStartPoint.y = CGRectGetMinY(pathRect);
myEndPoint.x   = CGRectGetMaxX(pathRect);
myEndPoint.y   = CGRectGetMinY(pathRect);

// draw the gradient
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetLineWidth(context, 5.0);
CGContextAddPath(context, path);
CGContextSaveGState(context);
CGContextClip(context);
CGContextDrawLinearGradient (context, gradientFill,
                             myStartPoint, myEndPoint, 0);
CGContextRestoreGState(context);

CGGradientRelease(gradientFill);
CGColorSpaceRelease(colorSpace);

}我想你需要一个径向梯度。请参阅此苹果文档


在我看来,产生的梯度就像是燃油表的背景,因此径向梯度可能不会产生适当的效果。我对石英没有太多经验,但我的想法是用背景色填充椭圆

radius -= 5.0;
CGRect rainbowArch = CGRectMake( x - radius, y - radius, 2 * radius, 2 * radius);
const CGFloat * bgComponents = CGColorGetComponents( self.backgroundColor.CGColor );
CGContextSetRGBFillColor(context, bgComponents[0], bgComponents[1], bgComponents[2], 1.0);
CGContextFillEllipseInRect( context, rainbowArch );

...
CGContextRestoreGState(context);

CGGradientRelease(gradientFill);
CGColorSpaceRelease(colorSpace);


链接文档甚至显示了一个例子(图8-2),这是OP想要的,但不是径向的。应该是一个很好的起点来解释这个过程。