当用户在我的视图中选择位置x,y时,如何在圆形路径中添加16个点 并且点应该是相等的距离,
所以当用户点击视图中的某个位置时,我将用16点完成圆圈, 见附件。
图像是使用此代码:
CGPoint CenterPoint = CGPointMake(self.frame.size.width / 2, self.frame.size.height / 2);
CGPoint Point;
float Angel = 360/16;
for (int i = 0 ; i < 16;i++)
{
float distance = [self distanceFrom:newPoint to:centerPoint];
Point.x = CenterPoint.x + distance * cos(Angel);
Point.y = CenterPoint.y + distance * sin(Angel);
CGContextMoveToPoint(cacheContext, Point.x, Point.y);
CGContextAddLineToPoint(cacheContext, Point.x, Point.y);
CGContextStrokePath(cacheContext);
Angel+= 10;
}
答案 0 :(得分:0)
检查以下代码,它可能对您有所帮助
int startAngle = 0;
while (startAngle < 360)
{
CAShapeLayer *slice = [CAShapeLayer layer];
slice.fillColor = _buttonColor.CGColor;
slice.strokeColor = [UIColor clearColor].CGColor;
slice.lineWidth = 3.0;
CGFloat angle = DEGREES_TO_RADIANS(-60.0);
CGPoint center = CGPointMake(self.frame.size.width/2.0, self.frame.size.height/2.0);
CGFloat radius = self.frame.size.width/2.0;
UIBezierPath *piePath = [UIBezierPath bezierPath];
[piePath moveToPoint:center];
//[piePath addLineToPoint:CGPointMake(center.x + radius * cosf(DEGREES_TO_RADIANS(startAngle)), center.y + radius * sinf(DEGREES_TO_RADIANS(startAngle)))];
[piePath addArcWithCenter:center radius:radius startAngle:DEGREES_TO_RADIANS(startAngle) endAngle:DEGREES_TO_RADIANS(startAngle + 63) clockwise:YES];
// [piePath addLineToPoint:center];
[piePath closePath]; // this will automatically add a straight line to the center
slice.path = piePath.CGPath;
startAngle += (360/15);
[self.layer addSublayer:slice];
}
答案 1 :(得分:0)
cos
和sin
函数预计角度以弧度而非度数(您提供的角度)。请尝试这种替代方法。
float distance = [self distanceFrom:newPoint to:centerPoint];
CGContextSaveGState(cacheContext);
CGContextTranslateCTM(cacheContext, CenterPoint.x, CenterPoint.y);
for (int i = 0 ; i < 16;i++)
{
float angle = i * (M_2_PI / 16);
CGPoint pt = CGPointMake(distance * cos(angle), distance * sin(angle));
CGContextMoveToPoint(cacheContext, 0, 0);
CGContextAddLineToPoint(cacheContext, pt.x, pt.y);
CGContextStrokePath(cacheContext);
}
CGContextRestoreGState(cacheContext);
这种方法可以翻译上下文,使得原点(a.k.a中心点)确实是CenterPoint
,因此您无需担心将CenterPoint
添加到任何内容中。由于distance
不受循环内部任何内容的影响,因此应将其移出,以免不必要地重新计算。