iOS 绘制不规则的图形

逻辑分析

主要的逻辑:

  1. 设置不规则图形的顶点;
  2. 获取当前的上下文;
  3. CGContextBeginPath(context);
  4. 顶点连线;
  5. 设置填充颜色;
  6. CGContextClosePath(context);
  7. 填充颜色;

具体代码

设置一个属性为points,在set方法内去调用重新绘制图形;

1
2
3
4
- (void)setPoints:(NSArray *)points{
_points = points;
[self setNeedsDisplay];
}

重写UIView的方法drawRect:,实现绘图;

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
- (void)drawRect:(CGRect)rect{
CGPoint p[self.points.count];

if (self.points.count < 3) {
return;
}

for (int i = 0; i < self.points.count; i ++) {
CGPoint tempPoint = CGPointFromString([self.points objectAtIndex:i]);
p[i].x = tempPoint.x;
p[i].y = tempPoint.y;
}

CGContextRef context = UIGraphicsGetCurrentContext();
CGContextBeginPath(context);
CGContextAddLines(context, p, self.points.count);
[[UIColor colorWithRed:39/255.0 green:170/255.0 blue:226/255.0 alpha:1] setFill];
CGContextClosePath(context);
CGContextFillPath(context);

}

注意:CGContextAddLines这个方法的第二个参数是个C的数组,也可以说是指针;

总结

经常会忘记的,就是beginPath这个动作,和closePath是成对出现的。