我在iPhone应用程序中使用CGContextAddArc绘制了几个闭合形状,我想对其应用渐变,但找不到任何好的示例。我发现的所有剪辑到绘制形状的边界都在某个地方引用CGRect,但我需要将渐变边界剪辑到非CGRect形状。有什么想法/帮助吗?
我将xcode 4.2.1与故事板和iOS5一起使用,尽管这些形状是在视图中以编程方式绘制的。
我用来画非正方形的代码:
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 );
您正在寻找CGContextClip
函数,或者可能是CGContextEOClip
函数。
CGContextClip
将上下文的剪切路径设置为其当前剪切路径和当前路径的交点,然后清除当前路径。CGContextEOClip
也做同样的事情,但用不同的方式处理路径中的"洞"。只有当路径与自身相交或包含多个闭合子路径时,差异才重要。