2013-08-26 43 views
0

所以我目前正在嘗試創建一個網格/電影覆蓋與UIView。UIView與多元DrawRect方法

我創建了一些方法; drawVerticalLine和水平線和東西...

我有一個UIViewController,它位於UIGridView中。我可以把我所有的方法放在繪圖矩形中,並一次畫出它們。

但是,我想能夠從ViewController單獨調用它們。當我嘗試做enter code here那。我得到一個「:CGContextDrawPath:無效上下文0x0」代碼如下。 在我的ViewController中,我希望能夠調用「drawGrid:withColor:andLines;」什麼

- 

(void)drawRect:(CGRect)rect 
{ 

    if (self.verticalLinesON == YES) { 
     [self drawVerticalLinesForGrid:100 :[UIColor redColor] :[UIColor greenColor]]; 

    } 

    [self show16NineOverLay:[UIColor orangeColor]]; 

    [self show4ThreeOverLay:[UIColor orangeColor]]; 

    [self drawHorizontalLinesForGrid:100 :[UIColor blueColor] :[UIColor yellowColor]]; 

} 
-(void)drawVerticalLinesForGrid:(float)sectionsVertically :(UIColor *)lineColor1 :(UIColor *)lineColor2 
{ 
    CGContextRef context = UIGraphicsGetCurrentContext(); 
    CGContextSetLineWidth(context, 2); 
    int i = 0; 
    float amountOfSectionsVertically = sectionsVertically; 
    for (i = 1; i < amountOfSectionsVertically; i++) 
    {//Horizontal Lines first. 
     float xCoord = self.frame.size.width * ((i+0.0f)/amountOfSectionsVertically); 
     CGContextMoveToPoint(context, xCoord, 0); 
     CGContextAddLineToPoint(context, xCoord, self.frame.size.height); 
     if (i%2 == 1) 
     {//if Odd 
      CGContextSetStrokeColorWithColor(context, lineColor1.CGColor); 
     } 
     else if(i%2 == 0) 
     {//if Even 
      CGContextSetStrokeColorWithColor(context, lineColor2.CGColor); 
     } 
     CGContextStrokePath(context); 
    } 
} 
-(void)drawHorizontalLinesForGrid :(float)sectionsHorizontally :(UIColor *)lineColor1 :(UIColor *)lineColor2 
{ 
    CGContextRef context = UIGraphicsGetCurrentContext(); 
    CGContextSetLineWidth(context, 2); 
    int i = 0; 
    float amountOfSectionsHorizontally = sectionsHorizontally; 
    for (i = 1; i < amountOfSectionsHorizontally; i++) 
    {//Vertical Lines first. 
     float yCoord = self.frame.size.height * ((i+0.0f)/amountOfSectionsHorizontally); 
     CGContextMoveToPoint(context, 0, yCoord); 
     CGContextAddLineToPoint(context, self.frame.size.width, yCoord); 
     if (i%2 == 1) 
     {//if Odd 
      CGContextSetStrokeColorWithColor(context, lineColor1.CGColor); 
     } 
     else if(i%2 == 0) 
     {//if Even 
      CGContextSetStrokeColorWithColor(context, lineColor2.CGColor); 
     } 
     CGContextStrokePath(context); 
    } 
} 
-(void)show16NineOverLay:(UIColor *)lineColor 
{ 
    CGContextRef context = UIGraphicsGetCurrentContext(); 
    CGContextSetLineWidth(context, 10); 
    //x/y 
    float yCoord = (0.5) * (self.frame.size.height * (1.778) 

回答

1

你應該做的是設置上,以指定應繪製網格視圖類的一些狀態(只是垂直,水平只是,無論是等),然後調用視圖setNeedsDisplay

這將觸發drawRect:的呼叫。然後你的drawRect:方法應該看看它的當前狀態,並調用適當的方法來繪製所需的部分。

您絕對不能直接在視圖上調用drawRect:

+0

是的,那是我的工作。我製作了「setgrid/vertlines/otherstuff」方法,並將它們全部添加到ViewDidLoad中。我把它們放在If語句中,並創建BOOL變量來決定是否應該調用它們。我設置了這些BOOL以及線條粗細,顏色 – DTDev