饼图/快速绘图 [英] pie chart/plot in swift
问题描述
我尝试了很多不同的方法来从GitHub添加绘图程序包,使用核心绘图或将Objective-C组合到Swift中,但是在此过程中出现了很多问题,在这一周中,我没有取得成功图表.我真的很沮丧
I've tried so many different ways of add plots package from GitHub or using core plots or combining objective-c into swift, but it appeared so many problems during the process, and during this week I didn't make a successful chart. I'm really depressed.
有人成功地迅速创建了饼图吗?类似的问题似乎没有成功的答案.
Is there anyone who succeed in creating a pie chart in swift? The similar questions seem don't have successful answers.
非常感谢您的帮助!
推荐答案
不要沮丧.您只需添加一个更具体的问题即可获得更多帮助.例如,如果您从头开始并尝试集成来自Github的plots程序包,则必须说出什么程序包,如何尝试将其集成,遇到什么错误等.
Don't be depressed. You just have to add a more specific question to get more help. For example, if you start from scratch and try to integrate a plots package from Github, you have to say what package, how did you try to integrate it, what errors are you getting etc.
但是,使用CoreGraphics功能可以很容易地绘制一个简单的饼图.这是我的代码提供的一点礼物,它以简单的黑白饼图形式绘制了进度值.它只有2个部分,但是您可以从中进行概括
However, drawing a simple pie chart is pretty easy with CoreGraphics functionality. Here is a little gift from my code, this draws progress value as a simple black and white pie chart. It only has 2 sections, but you can generalize from it
@IBDesignable class ProgressPieIcon: UIView {
@IBInspectable var progress : Double = 0.0 {
didSet {
self.setNeedsDisplay()
}
}
required init(coder aDecoder: NSCoder) {
super.init(coder:aDecoder)
self.contentMode = .Redraw
}
override init(frame: CGRect) {
super.init(frame: frame)
self.backgroundColor = UIColor.clearColor()
self.contentMode = .Redraw
}
override func drawRect(rect: CGRect) {
let color = UIColor.blackColor().CGColor
let lineWidth : CGFloat = 2.0
// Calculate box with insets
let margin: CGFloat = lineWidth
let box0 = CGRectInset(self.bounds, margin, margin)
let side : CGFloat = min(box0.width, box0.height)
let box = CGRectMake((self.bounds.width-side)/2, (self.bounds.height-side)/2,side,side)
let ctx = UIGraphicsGetCurrentContext()
// Draw outline
CGContextBeginPath(ctx)
CGContextSetStrokeColorWithColor(ctx, color)
CGContextSetLineWidth(ctx, lineWidth)
CGContextAddEllipseInRect(ctx, box)
CGContextClosePath(ctx)
CGContextStrokePath(ctx)
// Draw arc
let delta : CGFloat = -CGFloat(M_PI_2)
let radius : CGFloat = min(box.width, box.height)/2.0
func prog_to_rad(p: Double) -> CGFloat {
let rad = CGFloat(p * 2 * M_PI)
return rad + delta
}
func draw_arc(s: CGFloat, e: CGFloat, color: CGColor) {
CGContextBeginPath(ctx)
CGContextMoveToPoint(ctx, box.midX, box.midY)
CGContextSetFillColorWithColor(ctx, color)
CGContextAddArc(
ctx,
box.midX,
box.midY,
radius-lineWidth/2,
s,
e,
0)
CGContextClosePath(ctx)
CGContextFillPath(ctx)
}
if progress > 0 {
let s = prog_to_rad(0)
let e = prog_to_rad(min(1.0, progress))
draw_arc(s, e, color)
}
}
这篇关于饼图/快速绘图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!