views:

98

answers:

2

Hello, I'm trying to draw some lines inside my custom UIView.

From what I can see, to save messing around with CoreGraphics, I can use UIBezierPath (i've done similar with NSBezierPath on the Mac). I have some code that tries to draw the lines but I get output errors and can't find a decent reference with some sample code to illustrate whats going on, any ideas? Code below...

Code:

  - (void)drawRect:(CGRect)rect {
    // Drawing code
    UIBezierPath *line1 = [UIBezierPath bezierPath];
 [[UIColor blackColor] setStroke];
 [line1 setLineWidth:3];
 [line1 moveToPoint:CGPointMake(0, 0)];
 [line1 addLineToPoint:CGPointMake(320, 480)];
 [line1 stroke];

}

Errors:

Sat Oct  2 19:26:43 mercury.config mobileManual[46994] <Error>: CGContextSetStrokeColorWithColor: invalid context 0x0

UPDATE: Here's the current code, No errors but also no drawing.. ideas?

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];
    [self.view setBackgroundColor:[UIColor yellowColor]];
    [self.view setNeedsDisplay];
}

- (void)drawRect:(CGRect)rect {
    // Drawing code
    CGContextRef context = UIGraphicsGetCurrentContext(); 
    CGContextSaveGState(context);
    UIBezierPath *line1 = [UIBezierPath bezierPath];
    [line1 setLineWidth:3];
    [line1 moveToPoint:CGPointMake(0, 0)];
    [line1 addLineToPoint:CGPointMake(320, 480)];
    [line1 stroke];
    CGContextRestoreGState(context);
}
A: 

Your graphics context is invalid. This happens because:

  • You called drawRect: yourself. Never do that. Call setNeedsDisplay instead and have iOS call it.
  • You somehow destroyed the current graphics context (less likely).
Codo
ah that is making sense. Thank you. What is the syntax for UIGraphicsGetCurrentContext() ?
MightyLeader
See updated code in the question above, any thoughts as to where I am not handling this correctly? I have no errors but no drawing either.
MightyLeader
-1. You don't need to call UIGraphicsGetCurrentContext(); -[UIColor setStroke] does that for you.
tc.
A: 

Like I said above, your code is working fine for me.

Are you changing the "Class Identity" of the view in Interface Builder to your UIView subclass?

(As an aside, calling setNeedsDisplay in viewDidLoad is unnecessary, but it's also not hurting anything.)

Robot K
It's very surprising that the _Class Identity_ was the problem. If it's not correctly set, _drawRect:_ isn't called at all. But there were a lot of error messages from the function (see the original question).
Codo