2010-02-12 167 views
12

我一直在閱讀通過文檔,但它並不是立即清楚如何使用CGPath繪製多邊形。所有我需要做的是汲取CGPath周圍是這樣的:如何用CGPath繪製多邊形?

__ 
\ \ 
\ \ 
    \__\ 

任何人都可以請提供關於如何做到這一點的片段?

此外,我認爲CGPathContainsPoint將幫助我確定一個點是否這樣的路徑裏面?還是確實的路徑必須是固體描繪

此外,我怎麼能左右移動cgpath?就像在cgrect中那樣改變起源一樣簡單嗎?

謝謝。

-Oscar

回答

13

你應該做的是這樣的:

- (void)drawRect:(CGRect)rect { 

     CGContextRef context = UIGraphicsGetCurrentContext(); 

     CGContextSetStrokeColorWithColor(context, [UIColor redColor].CGColor); 
     CGContextSetRGBFillColor(context, 0.0, 0.0, 1.0, 1.0); 

     // Draw them with a 2.0 stroke width so they are a bit more visible. 
     CGContextSetLineWidth(context, 2.0); 

     for(int idx = 0; idx < self.points.count; idx++) 
     { 

      point = [self.points objectAtIndex:idx];//Edited 
      if(idx == 0) 
      { 
       // move to the first point 
       CGContextMoveToPoint(context, point.x, point.y); 
      } 
      else 
      { 
       CGContextAddLineToPoint(context, point.x, point.y); 
      } 
     } 

     CGContextStrokePath(context); 
} 

注意這裏,點是要繪製的多邊形點的陣列。所以它應該是圓形的路徑,如:你正在繪製一個三角點(x1, x2, x3)然後你應該傳入數組(x1, x2, x3, x1)

希望這會有所幫助。

+0

你不要在這裏引用一個數組,你剛纔反覆添加相同點。 – 2010-02-12 05:48:40

+1

@大衛我以爲這是理解 – 2010-02-12 11:00:58

+0

謝謝你的幫助。 – 2010-02-12 15:32:47

2

斯坦福大學的iPhone上的CS193P課程有一個名爲HelloPoly的項目,可能正是你想要的 - 看規範的class home page,然後看視頻是如何實現的(以及來自執行任務的人的谷歌解決方案)。

5

見蘋果的應用QuartzDemo。它具有執行此操作的代碼以及許多其他Quartz繪圖函數。

16

這是如何創建使用CGPath一個三角形的例子,你只需要放點。

var path = CGPathCreateMutable() 
CGPathMoveToPoint(path, nil, 0, 0) //start from here 
CGPathAddLineToPoint(path, nil, 20, 44) 
CGPathAddLineToPoint(path, nil, 40, 0) 
CGPathAddLineToPoint(path, nil, 0, 0) 

//and to use in SpriteKit, for example 

var tri = SKShapeNode(path: path) 
var color = NSColor.blueColor() 
tri.strokeColor = color 
tri.fillColor = color 

這是結果

Triangle with CGPath

+3

+1實際使用CGPath像想要的提問者。 – Tim 2014-08-30 01:30:54