2014-08-28 117 views
2

我試圖繪製自定義形狀使用UIBezierPath:填充UIBezierPath與平行線

UIBezierPath *aPath = [UIBezierPath bezierPath]; 

    [aPath moveToPoint:CGPointMake(100.0, 0.0)]; 

    // Draw the lines. 
    [aPath addLineToPoint:CGPointMake(200.0, 40.0)]; 
    [aPath addLineToPoint:CGPointMake(160, 140)]; 
    [aPath addLineToPoint:CGPointMake(40.0, 140)]; 
    [aPath addLineToPoint:CGPointMake(0.0, 40.0)]; 
    [aPath closePath]; 

我想用平行線填充它,使這個剝離。我也想改變這一行的顏色。 假設我想讓它們垂直。 我必須定期在這條路上計算點數,我該怎麼做?

我發現這個UIColor colorWithPatternImage,但然後我不能改變我的線內的形狀的顏色和「密度」。

回答

3

像尼古拉·魯赫說的,最好的選擇是用你的形狀作爲剪切路徑,然後在形狀的邊界框內畫出一些圖案。這是一個什麼樣的代碼是這樣

- (void)drawRect:(CGRect)rect 
{ 
    // create a UIBezierPath for the outline shape 
    UIBezierPath *aPath = [UIBezierPath bezierPath]; 
    [aPath moveToPoint:CGPointMake(100.0, 0.0)]; 
    [aPath addLineToPoint:CGPointMake(200.0, 40.0)]; 
    [aPath addLineToPoint:CGPointMake(160, 140)]; 
    [aPath addLineToPoint:CGPointMake(40.0, 140)]; 
    [aPath addLineToPoint:CGPointMake(0.0, 40.0)]; 
    [aPath closePath]; 
    [aPath setLineWidth:10]; 

    // get the bounding rectangle for the outline shape 
    CGRect bounds = aPath.bounds; 

    // create a UIBezierPath for the fill pattern 
    UIBezierPath *stripes = [UIBezierPath bezierPath]; 
    for (int x = 0; x < bounds.size.width; x += 20) 
    { 
     [stripes moveToPoint:CGPointMake(bounds.origin.x + x, bounds.origin.y)]; 
     [stripes addLineToPoint:CGPointMake(bounds.origin.x + x, bounds.origin.y + bounds.size.height)]; 
    } 
    [stripes setLineWidth:10]; 

    CGContextRef context = UIGraphicsGetCurrentContext(); 

    // draw the fill pattern first, using the outline to clip 
    CGContextSaveGState(context);   // save the graphics state 
    [aPath addClip];      // use the outline as the clipping path 
    [[UIColor blueColor] set];    // blue color for vertical stripes 
    [stripes stroke];      // draw the stripes 
    CGContextRestoreGState(context);  // restore the graphics state, removes the clipping path 

    // draw the outline of the shape 
    [[UIColor greenColor] set];    // green color for the outline 
    [aPath stroke];       // draw the outline 
} 
+0

非常感謝,我會盡力去做,如果發生其他問題,我會讓你知道。 – Preetygeek 2014-08-28 08:12:38

1

最好的選擇是在上下文中設置要繪製爲剪切路徑(CGContextClip)的原始形狀。

現在,只需將所有平行線繪製到形狀的邊界框中即可。然後,您可以自由改變線條的顏色或距離。

+0

據我所知剪輯會限制我畫到這個'UIBezierPath'和空間的例子,即使我做的線長也不會去走形,是嗎? – Preetygeek 2014-08-28 08:01:15

+1

@Preetygeek準確。裁剪工作就像一個面具,禁止顏色觸及形狀外的任何東西。您可以將所有內容繪製到此蒙版(形狀,文字,圖像)中。 – 2014-08-28 08:57:21

1

我目前還沒有這方面的代碼,但是您將沿着[UIColor colorWithPatternImage:...的正確路線行進。

但是,如果你想讓這更靈活,你可以編程生成圖像。

您只需要幾個像素的非常小的圖像。足夠的每種顏色的條紋之一。

如果你的條紋是綠色和紅色,綠色是4像素寬,紅色3像素寬,那麼你只需要一個像素寬和7像素高的圖像。

然後使用此自動生成的圖像作爲顏色的圖案圖像。

這可能是我能想到的最簡單的方法。

生成圖像不是很難。有關於繪製到圖像上下文中的許多SO問題。