我有一个自定义类,它管理一个自定义 View ,该 View 在屏幕上具有水平中心(将代表一条实线)。我画了这样的线:
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”循环还是?苹果有官方的图表API吗?
最佳答案
UIGraphicsGetCurrentContext()
为您提供了一个可以在其中绘制多个内容的上下文。称其为line
并不是正确的想法,因为它可以包含多条线、圆或各种其他东西。
将上下文想象为一位坐在空白 Canvas 前的艺术家。您向艺术家发出指示,例如“画一条红线,然后画一个蓝色圆圈”。艺术家按照说明进行操作,然后您查看 Canvas 。
以下是先画一条线,然后画一个圆的方法。
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 不提供“官方”产品。
关于swift - 在一条线上绘制多个圆 CGGraphicsContext,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36241969/