绘制虚线
虚线绘制主要调用CGContextSetLineDash函数。
这个函数有4个参数,除了一个是上下文外,phase为初始跳过几个点开始绘制,第三个参数为一个CGFloat数组,指定你绘制的样式,绘几个点跳几个点(下面为绘10个点,跳过5个),最后一个参数是上个参数数组元素的个数。
- (void)drawLineDash
{
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSaveGState(context);
CGContextSetLineWidth(context, 2.0f);
CGContextSetLineDash(context, 0, (CGFloat[]){10, 5}, 2);//绘制10个跳过5个
CGContextSetStrokeColorWithColor(context, [[UIColor brownColor] CGColor]);
CGContextMoveToPoint(context, 0, 20);
CGContextAddLineToPoint(context, 320, 20);
CGContextStrokePath(context);
CGContextRestoreGState(context);
}
效果如下:
绘制椭圆与圆
CGContextAddEllipseInRect函数
函数比较简单,只需要上下文和一个矩形参数。默认系统会绘制填充这个矩形内部的最大椭圆,若矩形为正方形,则为圆。
- (void)drawEllipse
{
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSaveGState(context);
CGContextAddEllipseInRect(context, CGRectMake(40, 180, 240, 120));
CGContextSetLineWidth(context, 3.0f);
CGContextSetStrokeColorWithColor(context, [[UIColor blueColor] CGColor]);
CGContextStrokePath(context);
CGContextRestoreGState(context);
}
效果
绘制弧,饼图(Pie Chart)
CGContextAddArc函数是一个画弧的函数,使用并不难,与其他一样,按照参数要求给其赋值就可以了,而且这个函数也十分好用,可以借助其实现绘制扇形,绘制饼图。
简单的看下这个函数
void CGContextAddArc (
CGContextRef c,
CGFloat x, 圆心点坐标的x和y
CGFloat y,
CGFloat radius, 半径
CGFloat startAngle, 绘制起始点的弧度值,一般在IOS绘图里都使用弧度这个概念
CGContextRef c,
CGFloat x, 圆心点坐标的x和y
CGFloat y,
CGFloat radius, 半径
CGFloat startAngle, 绘制起始点的弧度值,一般在IOS绘图里都使用弧度这个概念
CGFloat endAngle,绘制终点的弧度值
int clockwise 1为顺时针,0为逆时针。
);
int clockwise 1为顺时针,0为逆时针。
);
首先为了方便,我写了一个绘制饼图各个部分的函数。
void drawPieChart(CGContextRef context, CGPoint point, float start_angel, float end_angle, double radius, CGColorRef color)
{
CGContextMoveToPoint(context, point.x, point.y);
CGContextSetFillColorWithColor(context, color);
CGContextAddArc(context, point.x, point.y, radius, start_angel, end_angle, 0);
CGContextFillPath(context);
}
然后进行绘制
#define RADIANS(x) ((x)*(M_PI)/180)获取弧度
- (void)drawRect:(CGRect)rect
{
// Drawing code
// [self drawLineDash];
// [self drawEllipse];
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSaveGState(context);
CGContextSetShadow(context, CGSizeMake(0, 10), 10); //简单的设置了一个阴影
double radius = 120;
float start = RADIANS(0);
float end = RADIANS(120);
drawPieChart(context, self.center, start, end, radius, [[UIColor orangeColor] CGColor]);
start = end;
end = RADIANS(194);
drawPieChart(context, self.center, start, end, radius, [[UIColor yellowColor] CGColor]);
start = end;
end = RADIANS(231);
drawPieChart(context, self.center, start, end, radius, [[UIColor purpleColor] CGColor]);
start = end;
end = RADIANS(360);
drawPieChart(context, self.center, start, end, radius, [[UIColor blueColor] CGColor]);
CGContextRestoreGState(context);
}
效果
以上为本篇博客全部内容,欢迎指正和交流。如需转载请注明出处~