user472292
user472292

Reputation: 329

Draw a Path - iPhone

I am animating an object along a path on the iPhone. The code works great using CAKeyframeAnimation. For debugging purposes, I would like to draw the line on the screen. I can't seem to do that using the current CGContextRef. Everywhere I look it says you need to subclass the UIView then override the drawRect method to draw on the screen. Is there anyway around this? If not, how do I pass data to the drawRect method so it knows what do draw?

EDIT: Ok. I ended up subclassing UIView and implementing the drawing in the drawRect method. I can get it to draw to the screen by creating another method in the subclassed view (called drawPath) that sets an instance variable then calls setNeedsDisplay. That in turn fires the drawRect method which uses the instance variable to draw to the screen. Is this the best practice? What happens if I want to draw 20+ paths. I shouldn't have to create properties for all of these.

Upvotes: 1

Views: 1560

Answers (2)

Ved
Ved

Reputation: 612

In your drawRect method of UIView put some code like this

    CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetRGBStrokeColor(context, 1.0, 0,0 , 0.0);
CGContextSetLineWidth(context, 3.f);

CGContextBeginPath(context);
CGContextMoveToPoint(context,x1,y1);

CGContextAddLineToPoint(context, x2 , y2);
CGContextStrokePath(context);

Upvotes: 6

Davyd Geyl
Davyd Geyl

Reputation: 4623

If you want to use Core Graphics drawing use CALayer. If you do not want to subclass it, delegate drawing to the view.

- (id)initWithFrame:(CGRect)frame 
{
    self = [super initWithFrame:frame];
    if (self) 
    {
       CALayer* myLayer = [CALayer new];
       myLayer.delegate = self;
       self.layer = myLayer;
    }
}

- (void)drawLayer:(CALayer *)layer inContext:(CGContextRef)ctx
{
  // draw your path here
}

Do not forget to call [self.layer setNeedsDisplay]; when you need to redraw it.

Upvotes: 0

Related Questions