2012-01-09 45 views
1

我有一些使用CGContextAddArc在iPhone應用程序中繪製的閉合形狀,並且我想對其應用漸變,但不能找到任何好的例子。我發現所有剪輯都被綁定到某個繪製的形狀引用CGRect,但我需要將漸變邊界剪裁爲非CGRect形狀。任何想法/幫助?將漸變應用於使用AddArc繪製的非正方形形狀

我使用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); 

回答

1

您正在尋找CGContextClip功能,或者也許是CGContextEOClip功能。

CGContextClip將上下文的剪切路徑設置爲其當前剪切路徑與其當前路徑的交點,然後清除當前路徑。 CGContextEOClip也是如此,但採用不同的方式處理路徑中的「洞」。如果您有一條與其自身相交的路徑,或者包含多個已關閉的子路徑,則不同之處很重要。

+0

是的!那樣做了。感謝您的幫助,並感謝(長)延遲確認。 – Amos 2012-01-21 02:55:16