因为一个图标分析的界面,想要画出一个多边形,搜索了一下,发现都不大靠谱,还是自己写一个吧,写完发现,其实不难啊,人懒不成事儿,这话说的真不假!!!
主要的逻辑:
- 计算半径,我们按照中心点作为标准,最短边的一半做为半径;
- 根据圆周率以及角度运算计算坐标点;
- 连线;
- 绘制图形;
以下的代码以右侧端点,按照逆时针按照0度开始计算,依次算出count边形的各个端点;
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
| - (void)drawRect:(CGRect)rect { CGContextRef context = UIGraphicsGetCurrentContext(); CGContextSetStrokeColorWithColor(context, [UIColor whiteColor].CGColor); CGContextSetRGBFillColor(context, 0, 1, 1, 1); CGFloat lengths[] = {2,2}; CGContextSetLineDash(context, 0, lengths, 2); CGContextSetLineWidth(context, 2.0); if (self.count < 2) { return; } NSMutableArray *points = [NSMutableArray arrayWithCapacity:self.count]; CGPoint circlePoints[self.count+1]; CGFloat width = CGRectGetWidth(self.bounds); CGFloat height = CGRectGetHeight(self.bounds); CGFloat radius = ABS((width < height ? width : height)/2.0); for (int i = 1 ; i <= self.count; i ++){ CGPoint tempPoint = CGPointZero; tempPoint.x = width/2.0 + radius * cos(2*i*M_PI/self.count); tempPoint.y = height/2.0 - radius * sin(2*i*M_PI/self.count); [points addObject:NSStringFromCGPoint(tempPoint)]; circlePoints[i-1].x = tempPoint.x; circlePoints[i-1].y = tempPoint.y; if (i == 1) { circlePoints[self.count].x = tempPoint.x; circlePoints[self.count].y = tempPoint.y; }
CGPoint centerPoint = CGPointMake(width/2, height/2); CGContextMoveToPoint(context, centerPoint.x, centerPoint.y); CGContextAddLineToPoint(context, tempPoint.x, tempPoint.y); } CGContextAddLines(context, circlePoints, self.count+1); CGContextStrokePath(context); }
|
需求上,还要求,再这个图形的基础上,绘制出一个不同剃度的不规则的图形,后续将会补充说明处理过程;