UIBezierPath对象是CGPathRef数据类型的封装.
使用moveToPoint: 和 addLineToPoint:去创建一个矩形。
- (void)drawRect:(CGRect)rect
{
[[UIColor orangeColor] set];//设置线条颜色
UIBezierPath *path = [UIBezierPath bezierPath];
path.lineWidth = 1.0;
path.lineCapStyle = kCGLineCapRound;//线条拐角
path.lineJoinStyle = kCGLineJoinRound;//连接形式
//设置起点
[path moveToPoint:CGPointMake(100.0, 100.0)];
//画线
[path addLineToPoint:CGPointMake(200.0, 100.0)];
[path addLineToPoint:CGPointMake(200.0, 200.0)];
[path addLineToPoint:CGPointMake(100.0, 200.0)];
[path closePath];
[path stroke];
}
也可以使用+ (UIBezierPath *)bezierPathWithRect:(CGRect)rect来创建矩形
- (void)drawRect:(CGRect)rect
{
[[UIColor blueColor] set];
UIBezierPath *path = [UIBezierPath bezierPathWithRect:CGRectMake(100, 100, 100, 100)];
path.lineWidth = 5.0;
//填充矩形
[path fill];
}
使用+ (UIBezierPath *)bezierPathWithOvalInRect:(CGRect)rect 根据矩形框画内切圆
当传入的rect是一个正方形时,绘制的图像是一个内切圆;当传入的rect是一个长方形时,绘制的图像是一个内切椭圆。
- (void)drawRect:(CGRect)rect
{
[[UIColor orangeColor] set];
UIBezierPath *path = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(100, 100, 100, 100)];
[path stroke];
}
使用+ (UIBezierPath *)bezierPathWithRoundedRect:(CGRect)rect cornerRadius:(CGFloat)cornerRadius 绘制带圆角的矩形
- (void)drawRect:(CGRect)rect
{
[[UIColor orangeColor] set];
UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:CGRectMake(100, 100, 100, 100) cornerRadius:15];
[path fill];
}
使用+ (UIBezierPath *)bezierPathWithRoundedRect:(CGRect)rect byRoundingCorners:(UIRectCorner)corners cornerRadii:(CGSize)cornerRadii
画指定某个角为圆角的矩形
参数:
corners:枚举值,可以选择某个角
cornerRadii:圆角的大小
- (void)drawRect:(CGRect)rect
{
[[UIColor blueColor] set];
UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:CGRectMake(100, 100, 100, 100) byRoundingCorners:UIRectCornerBottomLeft | UIRectCornerTopRight cornerRadii:CGSizeMake(15, 15)];
[path fill];
}
以某个中心点画弧线 + (UIBezierPath *)bezierPathWithArcCenter:(CGPoint)center radius:(CGFloat)radius startAngle:(CGFloat)startAngle endAngle:(CGFloat)endAngle clockwise:(BOOL)clockwise;
参数:
center:弧线中心点的坐标
radius:弧线所在圆的半径
startAngle:弧线开始的角度值
endAngle:弧线结束的角度值
clockwise:是否顺时针画弧线
例如,如下所示的弧线:
代码如下:
- (void)drawRect:(CGRect)rect
{
[[UIColor blueColor] set];
UIBezierPath *path = [UIBezierPath bezierPathWithArcCenter:CGPointMake(150, 150) radius:75 startAngle:0 endAngle:DEGREES_TO_RADIANS(135) clockwise:YES];
[path stroke];
}
绘制一个扇形
UIBezierPath *piePath = [UIBezierPath bezierPath];
CGPoint center = self.center;
[piePath moveToPoint:center];
[piePath addArcWithCenter:center radius:100 startAngle:0 endAngle:M_PI *3 / 4 clockwise:YES];
[piePath closePath];
[piePath fill];