我使用CGContextAddArc在iPhone应用程序中绘制了几个封闭的形状,我想对它应用渐变,但找不到任何好的例子。我发现剪辑绑定到绘制的形状参考CGRect某处,但我需要将渐变边界剪切为非CGRect形状。任何想法/帮助?
我正在使用带有故事板和iOS5的xcode 4.2.1,尽管这些形状是以编程方式在视图中绘制的。
我用来绘制非方形形状的代码:
CGContextRef context = UIGraphicsGetCurrentContext();
//set context-based constants
double widthMiddle = self.frame.size.width/2;
double heightMiddle = self.frame.size.height/2;
double avgDimension = (widthMiddle + heightMiddle) / 2;
float arcRadius = avgDimension * .9;
float innerRadius = avgDimension * .4;
double startAngle = 2 * (sectionNumber - 1) * (M_PI / 3);
double endAngle = (2 * (sectionNumber * (M_PI / 3))) - [sectionSpacing doubleValue];
double interfaceAngle = [sectionSpacing doubleValue] * (innerRadius / arcRadius);
double ratingRadius = innerRadius + ((arcRadius-innerRadius) * percentGood);
double percentInterfaceAngle = interfaceAngle * (1-percentGood);
//NSLog(@"InterfaceAngle and percentInterfaceAngle are: %f/%f", interfaceAngle, percentInterfaceAngle);
//draw grey background shape
CGContextBeginPath(context);
CGContextSetLineWidth(context, [lineWeight doubleValue]);
//CGContextSetStrokeColorWithColor(context, [UIColor blueColor].CGColor);
CGContextSetRGBStrokeColor(context, .65, .65, .65, 1);
CGContextSetAllowsAntialiasing(context, 1);
//outer arc
CGContextAddArc(context, //context
widthMiddle, //X-value for center point of arc
heightMiddle, //Y-value for center point of arc
arcRadius, //Radius of the arc
startAngle, //start angle in radians
endAngle, //end angle in radians (2pi = full circle)
0); //Clockwise? 1 = true
//inner arc
CGContextAddArc(context, //context
widthMiddle, //X-value for center point of arc
heightMiddle, //Y-value for center point of arc
innerRadius, //Radius of the arc
endAngle - interfaceAngle, //start angle in radians
startAngle + interfaceAngle, //end angle in radians (2pi = full circle)
1); //Clockwise? 1 = true
CGContextClosePath(context);
//CGContextSetFillColorWithColor(context, [UIColor redColor].CGColor);
CGContextSetRGBFillColor(context, .65, .65, .65, 1);
//CGContextSetAlpha(context, .6);
CGContextDrawPath(context, kCGPathFillStroke );
答案 0 :(得分:1)
您正在寻找CGContextClip
功能,或者CGContextEOClip
功能。
CGContextClip
将上下文的剪切路径设置为其当前剪切路径与其当前路径的交集,然后清除当前路径。 CGContextEOClip
做同样的事情,但用不同的方式处理路径中的“漏洞”。如果您有一条与自身相交的路径,或者包含多个已关闭的子路径,那么这些路径才会有用。