iOS无法绘制简单的线条

时间:2012-11-22 04:03:50

标签: objective-c ios drawrect

- (void)drawRect:(CGRect)rect
{
CGFloat red[4] = {1.0f, 0.0f, 0.0f, 1.0f};
CGContextSetStrokeColor(c, red);
CGContextBeginPath(c);
CGContextMoveToPoint(c, 150.0f, 200.0f);
CGContextSetLineWidth(c, 5.0f);
CGContextAddLineToPoint(c, 50,300);
CGContextAddLineToPoint(c, 260,300);
CGContextClosePath(c);
}

这是我的viewwillappear

-(void)viewWillAppear:(BOOL)animated
{
    [self.view setNeedsDisplay];         
}

但是,视图无法绘制线条而只是白色空白。

3 个答案:

答案 0 :(得分:1)

你试过这个吗?

- (void)drawRect:(CGRect)rect
    [super drawRect:rect];

    CGContextRef context    = UIGraphicsGetCurrentContext();

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

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


    CGContextMoveToPoint(context, 0,0); //start at this point

    CGContextAddLineToPoint(context, 20, 20); //draw to this point

    // and now draw the Path!
    CGContextStrokePath(context);
}

答案 1 :(得分:1)

您似乎在drawRect子类中使用UIViewController方法。但drawRect方法仅适用于UIView子类。

如果我是对的,请执行以下操作。另见@Anoop Vaidya的答案。这应该有效。

UIView进行子类化,在drawRect中执行所有操作,并将该视图添加到视图控制器中。

@interface myView : UIView
{

}
@end

@implementation myView

- (void)drawRect:(CGRect)rect{

}

@end

    -(void)viewWillAppear:(BOOL)animated
{
    myView *view1  = [[myView alloc]init];
    self.view =  view1;        
}

答案 2 :(得分:1)

你可以使用这个drawRect Tutorial,这对于先发而言非常有用。关于你的问题,确保你正在绘制的UIView是可见的视图,也许你要覆盖UIView或者在此视图之上还有其他视图,因此无法看到更改。也许你忘记在显示之前初始化视图。