我没有使用可可荚,因为我发现很难按照我想要的方式使用高级API制作图表。只是太复杂了。我希望对饼图的绘制方式进行较低级别的控制。
.
我自己画的馅饼区是这样的:
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
}
}
和APieChartSection
是一个简单结构:
struct PieChartSection {
let value: Double
let color: UIColor
let name: String
}
馅饼看起来不错,但标签有时离馅饼很远,有时离它很近:

我想问题是NSAttriutedString.draw
总是从左上角绘制文本,这意味着左上角文本与饼图的距离相等,而我需要绘制文本,以便最接近饼图的点与饼的距离相等。
我怎样才能画出那样的文字?
我没有使用可可荚,因为我发现很难按照我想要的方式使用高级API制作图表。只是太复杂了。我想对我的饼图的绘制方式进行较低级别的控制。