如何在饼图中找到标签的合适位置?

时间:2018-11-17 12:37:31

标签: ios swift charts drawing

我没有使用任何库,因此这不是this的副本。

我这样绘制自己的馅饼部分:

public void DeleteWordsFromText(string text, string[] wordsToDelete, char[] separators)
{
    Console.WriteLine(text);
    foreach (string word in wordsToDelete)
    {
        foreach(char separator in separators)
        {
            text = text.Replace(word + separator, String.Empty);
        }
    }
    Console.WriteLine("-------------------------------------------");
    Console.WriteLine(text);
}

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 } } 是一个简单的结构:

PieChartSection

馅饼看起来不错,但是标签有时离馅饼很远,有时甚至很近:

enter image description here

我认为问题在于struct PieChartSection { let value: Double let color: UIColor let name: String } 总是从左上角绘制文本,这意味着文本的左上角都与饼图等距,而我需要绘制文本,以使它们与饼图的最接近点都与饼图等距。

如何绘制这样的文字?

我没有使用可可豆,因为我发现很难按照我想使用高级API的方式制作图表。确实涉及太多的复杂性。我想要对饼图的绘制方式进行较低级别的控制。

1 个答案:

答案 0 :(得分:10)

  

我认为问题在于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)

结果:

enter image description here