Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to draw UIBezierPaths

Here's what I want to do:

I have a UIBezierPath and I want to pass it to some method for it to be drawn. Or simply draw it from the method in which it is created.

I'm not sure how to indicate which view it should be drawn in. Do all methods for drawing have to start with

- (void)drawRect:(CGRect)rect { ...} ?

can I do

- (void)drawRect:(CGRect)rect withBezierPath:(UIBezierPath*) bezierPath { ... } ??

How do I call this function, or method, from another method?

like image 589
Lordof Theflies Avatar asked Jun 22 '11 04:06

Lordof Theflies


2 Answers

drawRect: is something that is invoked automatically when you message setNeedsDisplay or setNeedsDisplayInRect: on a view. You never call drawRect: directly.

However you are right in saying that all drawing operations are done within the drawRect: method. Typical implementation would be,

- (void)drawRect:(CGRect)rect {
    CGContextRef context = UIGraphicsGetCurrentContext();

    /* Do your drawing on `context` */
}

Since you are using UIBezierPaths, you will need to maintain an array of bezier paths that you will need to draw and then call setNeedsDisplay when something changes.

- (void)drawRect:(CGRect)rect {    
    for ( UIBezierPath * path in bezierPaths ) {
        /* set stroke color and fill color for the path */
        [path fill];
        [path stroke];
    }
}

where bezierPaths is an array of UIBezierPaths.

like image 152
Deepak Danduprolu Avatar answered Oct 07 '22 20:10

Deepak Danduprolu


First, save your path in an ivar

@interface SomeView {
  UIBezierPath * bezierPath;
}
@property(nonatomic,retain) UIBezierPath * bezierPath;
...
@end
....
- (void)someMethod {
     self.bezierPath = yourBezierPath;
     [self setNeedsDisplayInRect:rectToRedraw];
}

in -drawRect:

- (void)drawRect:(CGRect)rect {
    CGContextRef currentContext = UIGraphicsGetCurrentContext();
    CGContextSetLineWidth(currentContext, 3.0);
    CGContextSetLineCap(currentContext, kCGLineCapRound);
    CGContextSetLineJoin(currentContext, kCGLineJoinRound);
    CGContextBeginPath(currentContext);
    CGContextAddPath(currentContext, bezierPath.CGPath);
    CGContextDrawPath(currentContext, kCGPathStroke);
}
like image 35
ZhangChn Avatar answered Oct 07 '22 22:10

ZhangChn