我有一个自定义类来管理自定义视图,该视图在屏幕上有一个水平中心(代表一条实线)。我画了这样的界线:
override func drawRect(rect: CGRect)
{
let line = UIGraphicsGetCurrentContext()
CGContextSetLineWidth(line, 3.0)
CGContextSetStrokeColorWithColor(line, UIColor.redColor().CGColor)
CGContextMoveToPoint(line, 0, self.bounds.midY)
CGContextAddLineToPoint(line, self.bounds.width, self.bounds.midY)
CGContextStrokePath(line)
}
但是,我需要在此行上绘制多个实心圆圈,并尝试将其视为图表中的一个点。我试图制作一个迷你图表表示。我怎么画圆圈?使用嵌套的'for in'循环或?是否有Apple的官方图表API?
答案 0 :(得分:1)
UIGraphicsGetCurrentContext()
为您提供了一个可以绘制多个内容的上下文。调用它line
不是正确的想法,因为它可以包含多行,或圆圈,或其他各种东西。
将环境视为坐在空白画布前的艺术家。你给艺术家指示,如“画一条红线,然后画一个蓝色的圆圈”。艺术家遵循指示,然后,你看画布。
以下是绘制直线和圆形的方法。
let context = UIGraphicsGetCurrentContext()
// Tell the context what stroked paths should look like
CGContextSetLineWidth(context, 3.0)
CGContextSetStrokeColorWithColor(context, UIColor.redColor().CGColor)
// Draw a single line
CGContextMoveToPoint(context, 0, self.bounds.midY)
CGContextAddLineToPoint(context, self.bounds.width, self.bounds.midY)
CGContextStrokePath(context)
// Now draw a circle by filling a path.
// First, set the fill color:
CGContextSetFillColorWithColor(context, UIColor.blueColor().CGColor)
// Specify how big the circle is, and where its center is:
let circleRadius = CGFloat(5.0)
let circleCenter = CGPoint(x: self.bounds.midX, y: self.bounds.midY)
// Then add a circle to the context, by specifying the rectangle that surrounds it:
let circleRect = CGRect(x: circleCenter.x - circleRadius,
y: circleCenter.y - circleRadius,
width: circleRadius * 2,
height: circleRadius * 2)
CGContextAddEllipseInRect(context, circleRect)
// And fill that circle:
CGContextFillPath(context)
如果您想在不同的地方绘制更多圈子,请再次拨打CGContextAddEllipseInRect
和CGContextFillPath
,但circleRect
的值不同。根据您的需要,for循环可能是合适的。这完全取决于你。
如果您不想自己编写,可以使用许多第三方图表库,只需进行搜索即可。 Apple没有提供“官方”版本。