热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

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

如何解决《如何在饼图中找到标签的合适位置?》经验,为你挑选了1个好方法。

我没有使用任何库,所以这是不是重复这个。

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

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)

结果:


推荐阅读
author-avatar
美猴qing_243
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有