前两天在项目开发中涉及到绘制圆形的需求,在这里记录下两种绘制圆的方法。
一、在- (void)drawRect:(CGRect)rect方法中使用Context进行绘制
CGContextRef context = UIGraphicsGetCurrentContext(); //得到图形上下文
CGContextSetFillColorWithColor(context, [UIColor grayColor].CGColor); //设置填充颜色
CGContextAddArc(context, self.bounds.size.width / 2, self.bounds.size.height / 2, (self.bounds.size.height - 60) / 2, 0, 2 * M_PI, 0); //添加圆的绘制路径
CGContextDrawPath(context, kCGPathFill); //绘制,<span style="font-family: Arial, Helvetica, sans-serif;">kCGPathFill表示绘制填充圆,KCGPathStroke表示绘制边框圆</span>
二、使用ShapeLayer和贝塞尔曲线绘制圆
CAShapeLayer *circleLayer = [[CAShapeLayer alloc] init];
circleLayer.fillColor = [UIColor redColor].CGColor;
UIBezierPath *circleBezierPath = [UIBezierPath bezierPathWithArcCenter:self.center radius:100 startAngle:0 endAngle:M_PI * 2 clockwise:YES];
circleLayer.path = circleBezierPath.CGPath;
[self.layer addSublayer:circleLayer];
也可以通过context和UIBezierPath的不同方法得到不同路径来绘制不同的图形。