gpt4 book ai didi

swift - 快速饼图/绘图

转载 作者:搜寻专家 更新时间:2023-10-31 19:35:17 25 4
gpt4 key购买 nike

我尝试了很多不同的方法,从 GitHub 添加 plots 包,或者使用 core plots,或者将 objective-c 结合到 swift 中,但是在这个过程中出现了很多问题,这周我没有成功图表。我真的很沮丧。

有没有人在swift中成功地创建了饼图?类似的问题似乎没有成功的答案。

非常感谢您的帮助!

最佳答案

不要沮丧。您只需添加更具体的问题即可获得更多帮助。例如,如果您从头开始并尝试从 Github 集成一个 plots 包,您必须说明是什么包,您是如何尝试集成它的,您遇到了什么错误等等。

但是,使用 CoreGraphics 功能绘制简单的饼图非常容易。这是我的代码的一个小礼物,它将进度值绘制为一个简单的黑白饼图。它只有 2 个部分,但您可以从中概括

@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)
}
}

关于swift - 快速饼图/绘图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28768550/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com