作者:美猴qing_243 | 来源:互联网 | 2022-11-29 14:39
我没有使用任何库,所以这是不是重复这个。
我自己绘制馅饼部分是这样的:
var sections: [PieChartSection] = [] {
didSet {
setNeedsDisplay()
}
}
override func draw(_ rect: CGRect) {
let sumOfSectiOns= sections.map { $0.value }.reduce(0, +)
var pathStart = CGFloat.pi
let smallerDimension = min(height, width)
for section in sections {
// draw section
let percentage = section.value / sumOfSections
let pathEnd = pathStart + CGFloat.pi * percentage.f * 2
let path = UIBezierPath(arcCenter: CGPoint(x: bounds.midX, y: bounds.midY),
radius: smallerDimension / 4, startAngle: pathStart, endAngle: pathEnd, clockwise: true)
//draw labels
// this is my attempt at calculating the position of the labels
let midAngle = (pathStart + pathEnd) / 2
let textX = bounds.midX + smallerDimension * 3 / 8 * cos(midAngle)
let textY = bounds.midY + smallerDimension * 3 / 8 * sin(midAngle)
// creating the text to be shown, don't this is relevant
let attributedString = NSMutableAttributedString(string: section.name, attributes: [
.foregroundColor: UIColor.black.withAlphaComponent(0.15),
.font: UIFont.systemFont(ofSize: 9)
])
let formatter = NumberFormatter()
formatter.maximumFractiOnDigits= 0
let percentageString = "\n" + formatter.string(from: (percentage * 100) as NSNumber)! + "%"
attributedString.append(NSAttributedString(string: percentageString, attributes: [
.foregroundColor: UIColor.black.withAlphaComponent(0.5),
.font: UIFont.systemFont(ofSize: 12)
]))
attributedString.draw(at: CGPoint(x: textX, y: textY))
// stroke path
path.lineWidth = 6
section.color.setStroke()
path.stroke()
pathStart = pathEnd
}
}
而a PieChartSection
是一个简单的结构:
struct PieChartSection {
let value: Double
let color: UIColor
let name: String
}
饼看起来不错,但标签有时离饼很远,有时甚至很近:
我认为问题是,NSAttriutedString.draw
总是吸引了来自左上角的文本,这意味着左上边角的文字是馅饼全部相等距离,而我需要绘制文本,以便他们的最近点的馅饼是到馅饼的距离都相等。
我该如何绘制这样的文字?
我没有使用可可豆荚,因为我发现很难按照我想使用高级API的方式制作图表。确实涉及太多的复杂性。我想要对饼图的绘制方式进行较低级别的控制。
1> pacification..:
我认为问题在于,NSAttriutedString.draw
总是从左上角绘制文本
当然,该draw
方法会将字符串的原点放在您通过的位置。在这种情况下,解决方案很简单-找到size
字符串,并指定正确的原点。
let size = attributedString.size()
let origin = CGPoint(x: textX - size.width / 2, y: textY - size.height / 2)
attributedString.draw(at: origin)
结果: