new_programmer
new_programmer

Reputation: 860

Draw Line in View : Not Drawing

I am trying to draw a line

my Code is this

-(void) drawRect:(CGRect) rect
{
    NSLog(@"Reached Draw ARect Function");

    CGContextRef ctx = UIGraphicsGetCurrentContext(); 
    CGContextSetLineWidth(ctx, 2.0);
    CGContextSetRGBStrokeColor(ctx, 1.0, 2.0, 0, 1); 
    CGContextMoveToPoint(ctx, 0, 0);
    CGContextAddLineToPoint( ctx, 100,100);

    CGContextStrokePath(ctx);

}

and i am calling from the viewDidLoad as follows

- (void)viewDidLoad {

    [super viewDidLoad];
    CGRect k = CGRectMake(1.0, 1.0, 100.0, 200.0);
    [self.view drawRect:k];

}

Can any one help me please?

Upvotes: 1

Views: 4655

Answers (3)

Ashok
Ashok

Reputation: 5655

If there is a need to call

- (void)drawRect:(CGRect)rect

method dynamically while user is dragging a particular view, just place the following code:

[self.view setNeedsDisplay];

then

- (void)drawRect:(CGRect)rect

method will automatically be called

Upvotes: 0

hotpaw2
hotpaw2

Reputation: 70673

You can't call drawRect directly.

Instead you call setNeedsDisplay on your UIView, return, and wait for the OS to call the UIView's drawRect with a proper context at some later time.

Upvotes: 0

epatel
epatel

Reputation: 46051

You should subclass a UIView and move your line drawing code to the drawRect: method, like you are doing (just hoping it's for a UIView subclass and not the UIViewController)

- (void)drawRect:(CGRect)rect {

   [super drawRect:rect];

   // Place your code here

}

You must also make sure you use the UIView subclass in InterfaceBuilder for the view you will be drawing into. You should not have to call this method yourself. If you want to animate something you should call the [view setNeedsDisplay]; to request a redraw of the view.



...and...you should add CGContextBeginPath(ctx); just before you call CGContextMoveToPoint

Upvotes: 3

Related Questions