使用多个DrawRect方法的UIView

时间:2013-08-26 21:10:43

标签: ios drawrect cgcontext

我目前正在尝试使用UIView创建一个Grid / Cinematic Overlay。

我创建了一些方法; drawVerticalLine和Horizo​​ntal Lines and stuff ...

我有一个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 个答案:

答案 0 :(得分:1)

你应该做的是在网格视图类上设置一些状态,指定应绘制的内容(只是垂直,只是水平,两者等),然后在视图上调用setNeedsDisplay

这将触发对drawRect:的调用。然后你的drawRect:方法应该查看它的当前状态,并调用恰当的方法来绘制所需的部分。

您绝不能直接在视图上调用drawRect: