如何绘制UIBezierPaths

这就是我想要做的:

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

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

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

我可不可以做

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

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

drawRect:是在视图上发送setNeedsDisplaysetNeedsDisplayInRect:时自动调用的内容。 你永远不会直接调用drawRect:

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

 - (void)drawRect:(CGRect)rect { CGContextRef context = UIGraphicsGetCurrentContext(); /* Do your drawing on `context` */ } 

由于您使用的是UIBezierPath ,因此您需要维护一个需要绘制的bezier路径数组,然后在出现更改时调用setNeedsDisplay

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

其中bezierPathsbezierPaths的数组。

首先,将您的路径保存在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); } 

当您需要自定义视图时,可以在子类上覆盖-drawRect:

 - (void)drawRect:(CGRect)rect { // config your context [bezierPath stroke]; } 

编辑:直接使用-stroke使代码更紧凑。

绘图只发生在名为-drawRect:的方法中(当视图被标记为需要通过setNeedsDisplay显示时自动调用)。 所以drawRect:withBezierPath:方法永远不会被自动调用。 它执行的唯一方法是你自己调用它。

但是,一旦你有了UIBezierPath ,就可以很容易地绘制它:

 - (void)drawRect:(CGRect)rect { UIBezierPath *path = ...; // get your bezier path, perhaps from an ivar? [path stroke]; } 

如果您想要做的只是绘制路径,则无需使用Core Graphics。

你可以做以下事情。 只需定义一个UIColor * setStroke; 在.h文件中你需要在调用之前设置这个strokeColor对象[myPath strokeWithBlendMode:kCGBlendModeNormal alpha:1.0];

  - (void)drawRect:(CGRect)rect { [strokeColor setStroke]; // this method will choose the color from the receiver color object (in this case this object is :strokeColor) for(UIBezierPath *_path in pathArray) [myPath strokeWithBlendMode:kCGBlendModeNormal alpha:1.0]; } #pragma mark - Touch Methods -(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { myPath=[[UIBezierPath alloc]init]; myPath.lineWidth = currentSliderValue; UITouch *mytouch=[[touches allObjects] objectAtIndex:0]; [myPath moveToPoint:[mytouch locationInView:self]]; [pathArray addObject:myPath]; } -(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event { UITouch *mytouch=[[touches allObjects] objectAtIndex:0]; [myPath addLineToPoint:[mytouch locationInView:self]]; [self setNeedsDisplay]; }