美文网首页Mac·iOS开发Swift
iOS开发利用UIBezierPath画饼状统计图

iOS开发利用UIBezierPath画饼状统计图

作者: 剑老师 | 来源:发表于2021-05-31 14:32 被阅读0次

    本文首发于公众号【一个老码农】

    有这样一个需求,有七个颜色赤、橙、黄、绿、青、蓝、紫分别占比为10%、25%、10%、10%、20%、15%、10%。画出饼状统计图来表示它们分别的占比,并显示出各自的颜色名称。
    思路如下:

    1. 此时我们便可以用UIBezierPath绘制出圆形
    2. CAShapeLayer根据它们各自的百分比以及path路径绘制出扇形。
    3. 然后根据扇形角度计算出各自扇形的中心点
    4. 循环创建label并显示颜色名,设置各个扇形中心点为label的中心点

    废话不多说,上代码:

    //封装的饼图类
    //6个颜色
    fileprivate let defaultColors = [UIColor.red, UIColor.orange, UIColor.yellow, UIColor.green, UIColor.cyan, UIColor.blue, UIColor.purple]
    class PieView: UIView {
        
        override init(frame: CGRect) {
            super.init(frame: frame)
        }
        
        //options:选项字符串
        //percents:百分比(转化为0 - 1的小数)
        func setData(options: [String], percents: [CGFloat]) {
            if options.count == 0 ||
                options.count != percents.count ||
                options.count > defaultColors.count {
                return
            }
            
            //设置饼状图中心点
            let centerX: CGFloat = frame.width/2
            let centerY: CGFloat = frame.height/2
            let centerPoint = CGPoint(x: centerX, y: centerY)
            //设置半径
            let radius = min(centerX, centerY)/2
            //获取展示数据总和
            var nums: CGFloat = 0
            for i in percents {
                nums += I
            }
            
            //绘制各个扇形的路径,从12点钟方向顺时针开始绘制
            let subPath = UIBezierPath(arcCenter: centerPoint, radius: radius, startAngle: CGFloat(-Double.pi/2), endAngle: CGFloat(Double.pi/2*3), clockwise: true)
            //设置各个扇形开始和结束位置
            var start: CGFloat = 0
            var end: CGFloat = 0
            for i in 0 ..< percents.count {
                end = percents[i]/nums + start
               
                if percents[i] != 0 {
                    let strokeColor = defaultColors[i].cgColor
                    
                    let subLayer = drawLayerWith(fillColor: UIColor.clear.cgColor, strokeColor: strokeColor, strokeStart: start, strokeEnd: end, zPosition: 2, lineWidth: radius*2/3, path: subPath.cgPath)
                    layer.addSublayer(subLayer)
                    //扇形角度
                    let angel = CGFloat(Double.pi) * (start + end) 
                    let labelCenterX = radius*sin(angel) + centerX
                    let labelCenterY = -radius*cos(angel) + centerY
                    //颜色名label
                    let label = createLabel(title: "\(options[i])", radius: radius)
                    label.center = CGPoint(x: labelCenterX, y: labelCenterY)
                    addSubview(label)
                }
                
                start = end
            }
        }
        
        private func createLabel(title: String, radius: CGFloat) -> UILabel {
            let label = UILabel(frame: CGRect(x: 0, y: 0, width: radius * 0.8, height: radius * 0.3))
            label.text = title
            label.textColor = .black
            label.textAlignment = .center
            label.font = UIFont.systemFont(ofSize: 15)
            label.layer.zPosition = 3
            label.sizeToFit()
            return label
        }
        
        /// 返回一个CAShapeLayer
        /// - Parameters
        ///   - fillColor   填充颜色
        ///   - strokeColor 填充路径的描边轮廓的颜色
        ///   - strokeStart 表示路径的起点,在[0,1]的范围内
        ///   - strokeEnd  表示路径的终点,在[0,1]的范围内
        ///   - zPosition   表示在superlayer中的位置
        ///   - lineWidth   填充路径的线宽
        ///   - path        表示要呈现形状的路径
        fileprivate func drawLayerWith(fillColor: CGColor,
                                       strokeColor: CGColor,
                                       strokeStart: CGFloat,
                                       strokeEnd: CGFloat,
                                       zPosition: CGFloat,
                                       lineWidth: CGFloat,
                                       path: CGPath) -> CAShapeLayer {
            let layer = CAShapeLayer()
            layer.fillColor = fillColor
            layer.strokeColor = strokeColor
            layer.strokeStart = strokeStart
            layer.strokeEnd = strokeEnd
            layer.zPosition = zPosition
            layer.lineWidth = lineWidth
            layer.path  = path
            return layer
        }
        
        required init?(coder: NSCoder) {
            fatalError("init(coder:) has not been implemented")
        }
    }
    
    
    //在外部调用代码
    let pie = PieView()
    view.addSubview(pie)
    pie.frame = CGRect(x: (view.frame.width - 250)/2, y: 100, width: 250, height: 250)
    let options = ["赤","橙","黄","绿","青","蓝","紫"]
    let percents: [CGFloat] = [0.1, 0.25, 0.1, 0.1, 0.2, 0.15, 0.1]
    pie.setData(options: options, percents: percents)
    

    效果图:

    image

    原文地址

    相关文章

      网友评论

        本文标题:iOS开发利用UIBezierPath画饼状统计图

        本文链接:https://www.haomeiwen.com/subject/qekbsltx.html