如何绘制一圈线

我想基本上做一个从0到100的虚线圆匹配值。 我不想得到10个不同的图像代表不同的10点增量。 我该怎么做?

在这里输入图像说明

像这样的东西

制作一个UIView的自定义子类。

覆盖drawRect。

其中,您将使用这些function:

  • UIGraphicsGetCurrentContext
  • CGContextBeginPath
  • 一些线条画function
  • CGContextClosePath
  • CGContextDrawPath

如果你查阅这些函数的文档,你会很快find你需要的函数的交叉引用。

虽然我不在iOS或Objective-C中,但这个概念是普遍的。

圆上任意点的位置可以描述为sin(angle)*radius,cos(angle)*radius 。 所以你可以按照这个概念(用伪代码)自己绘制一个这样的圆:

 drawCircle(radius, borderWidth, dashDensity) { int numberOfDashes = radius / dashDensity); float radsPerDash = pi * 2 / numberOfDashes; float innerRadius = radius - (borderWidth / 2); float outerRadius = radius + (borderWidth / 2); for(float angle = 0; angle < pi * 2; angle += radsPerDash) DrawLine(sin(angle)*innerRadius, cos(angle)*innerRadius, sin(angle)*outerRadius, cos(angle)*outerRadius); } 

你应该能够从这里看起来像你想要的。 你当然也可以使用一个魔法常数从radius自动计算dashDensity ,并使用线宽,因为你认为适合较粗的破折号。

对于一个半圆(例如85%的填充),改变循环的结束条件:

 for(float angle = 0; angle < (pi * 2 * 0.85); angle += radsPerDash) 

抱歉在这里说rtm ,但是这样做。 使用CGPathCreateMutableCGPathAddArc创build圆,然后使用CGPathCreateCopyByDashingPath 。 完成。