如何绘制UIBezierPaths

Lor*_*ies 5 objective-c ios uibezierpath

这就是我想要做的事情:

我有一个UIBezierPath,我想将它传递给一些方法来绘制它.或者只是从创建它的方法中绘制它.

我不确定如何指出应该绘制哪个视图.所有绘图方法都必须从头开始

- (void)drawRect:(CGRect)rect { ...} ?
Run Code Online (Sandbox Code Playgroud)

我可不可以做

- (void)drawRect:(CGRect)rect withBezierPath:(UIBezierPath*) bezierPath { ... } ??
Run Code Online (Sandbox Code Playgroud)

如何从其他方法调用此函数或方法?

Dee*_*olu 20

drawRect:是您在消息setNeedsDisplaysetNeedsDisplayInRect:视图上自动调用的内容.你永远不会drawRect:直接打电话

但是你说的是所有的绘图操作都是在drawRect:方法中完成的.典型的实施方式是,

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

    /* Do your drawing on `context` */
}
Run Code Online (Sandbox Code Playgroud)

由于您使用UIBezierPath的是s,因此需要维护一个bezier路径数组,您需要绘制这些路径,然后setNeedsDisplay在发生变化时调用.

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

在哪里bezierPaths是一个UIBezierPaths 数组.


Zha*_*Chn 6

首先,将您的路径保存在ivar中

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

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);
}
Run Code Online (Sandbox Code Playgroud)