以几个例子来说明UIBezierPath的使用。
1.
UIBezierPath *aPath = [UIBezierPath bezierPath];
// Set the starting point of the shape.
[aPath moveToPoint:CGPointMake(100.0, 0.0)];
// Draw the lines.
[aPath addLineToPoint:CGPointMake(200.0, 40.0)];
[aPath addLineToPoint:CGPointMake(160, 140)];
[aPath addLineToPoint:CGPointMake(40.0, 140)];
[aPath addLineToPoint:CGPointMake(0.0, 40.0)];
[aPath closePath];
moveToPoint:方法,移动到此位置开始。之后可以画线addLineToPoint:。
类似这个画多边形的使用,贝塞尔曲线可以用来画圆,椭圆,矩形。大家可以在文档里看到各个方法的使用。
2.
// Create the path data.
CGMutablePathRef cgPath = CGPathCreateMutable();
CGPathAddEllipseInRect(cgPath, NULL, CGRectMake(0, 0, 300, 300));
CGPathAddEllipseInRect(cgPath, NULL, CGRectMake(50, 50, 200, 200));
// Now create the UIBezierPath object.
UIBezierPath *aPath = [UIBezierPath bezierPath];
aPath.CGPath = cgPath;
aPath.usesEvenOddFillRule = YES;
// After assigning it to the UIBezierPath object, you can release
// your CGPathRef data type safely.
CGPathRelease(cgPath);
UIBezierPath就是一个对CGPathRef数据的包装。可以直接对CGPathRef数据处理,并赋值给UIBezierPath对象。
3.
- (void)drawRect:(CGRect)rect
{
// Create an oval shape to draw.
UIBezierPath *aPath = [UIBezierPath bezierPathWithOvalInRect:
CGRectMake(0, 0, 200, 100)];
// Set the render colors.
[[UIColor blackColor] setStroke];
[[UIColor redColor] setFill];
CGContextRef aRef = UIGraphicsGetCurrentContext();
// If you have content to draw after the shape,
// save the current state before changing the transform.
//CGContextSaveGState(aRef);
// Adjust the view's origin temporarily. The oval is
// now drawn relative to the new origin point.
CGContextTranslateCTM(aRef, 50, 50);
// Adjust the drawing options as needed.
aPath.lineWidth = 5;
// Fill the path before stroking it so that the fill
// color does not obscure the stroked line.
[aPath fill];
[aPath stroke];
// Restore the graphics state before drawing any other content.
//CGContextRestoreGState(aRef);
}
以上就是把贝塞尔曲线展示出来的方法。
其中UIGraphicsGetCurrentContext()方法是用来获取当前的上下文。
CGContextTranslateCTM()方法用来做变换矩阵。
CGContextSaveGState和
CGContextRestoreGState方法用来保存和恢复当前的上下文,不受矩阵变换影响。
4.另外可以捕获贝塞尔曲线范围内的点击事件并做处理。
具体可以通过containsPoint: 方法。
5.另外,贝塞尔曲线还可以不在drawRect方法中使用。配合视图层,可以把贝塞尔曲线画出来。示例如下所示。
UIBezierPath * backStrokePath = [UIBezierPath bezierPath];
backStrokePath = [UIBezierPath bezierPathWithArcCenter:CGPointMake(self.frame.size.width/2, self.frame.size.height/2) radius:_object.radiousFlt startAngle:0 endAngle:M_PI*2 clockwise:YES];
//画线
CAShapeLayer *backStrokeShapeLayer = [[CAShapeLayer layer] retain];
backStrokeShapeLayer.path = backStrokePath.CGPath;
backStrokeShapeLayer.fillColor = [CommonTools colorWithHexString:_object.backColorStr].CGColor;
[self.layer addSublayer:backStrokeShapeLayer];
[backStrokeShapeLayer release];