2016-07-08 17 views
0

我想画出如图所示的两个半圆(如下图所示)如何绘制一个使用swift IO9的半圆,并基于一个数值绘制角度并填充颜色只有一部分

enter image description here 我 米数天努力,但没有得到任何 尝试了一些图表API和一些代码来绘制从计算器饼图,但他们需要编辑,我不知道核心Grahpics,因为我是新来的这 我工作在xcode 7.3.1和IOS 9 我的问题是: - 如何绘制一个半圆,取一个值并首先转换该值以获得其等效角度,然后dr AW这个角度的弧线和填充颜色在该部分 或提供我与我可以学习借鉴他们对我自己 感谢

回答

7

下面的代码在Xcode的iOS游乐场运行帮助一些链接。它创建一个自定义类UIView并绘制两个饼图片。起始角度和结束角度均以整圆的百分比表示。

您可以很容易地扩展它以显示更多或更少的切片,具体取决于您拥有的数据。

drawRect方法创建一个从中心开始的贝塞尔路径,然后添加一个弧段,最后关闭路径以便填充它。

import UIKit 

class PieChart : UIView { 

    override func drawRect(rect: CGRect) { 

     drawSlice(rect, startPercent: 0, endPercent: 50, color: UIColor.greenColor()) 
     drawSlice(rect, startPercent: 50, endPercent: 75, color: UIColor.redColor()) 
    } 

    private func drawSlice(rect: CGRect, startPercent: CGFloat, endPercent: CGFloat, color: UIColor) { 
     let center = CGPoint(x: rect.origin.x + rect.width/2, y: rect.origin.y + rect.height/2) 
     let radius = min(rect.width, rect.height)/2 
     let startAngle = startPercent/100 * CGFloat(M_PI) * 2 - CGFloat(M_PI) 
     let endAngle = endPercent/100 * CGFloat(M_PI) * 2 - CGFloat(M_PI) 
     let path = UIBezierPath() 
     path.moveToPoint(center) 
     path.addArcWithCenter(center, radius: radius, startAngle: startAngle, endAngle: endAngle, clockwise: true) 
     path.closePath() 
     color.setFill() 
     path.fill() 
    } 
} 

let pieChart = PieChart(frame: CGRect(x: 0.0, y: 0.0, width: 300.0, height: 300.0)) 
pieChart.backgroundColor = UIColor.clearColor() 
0

我的问题已解决。

我们只需要做的第一线变化不大,以使它像在图片的半圆:

drawSlice(rect, startPercent: 0, endPercent: 50, color: UIColor.greenColor()) 
drawSlice(rect, startPercent: 0, endPercent: 25, color: UIColor.redColor()) 
0

科多的代码在斯威夫特3:

import UIKit 

class PieChart : UIView { 

    override func draw(_ rect: CGRect) { 

     drawSlice(rect, startPercent: 0, endPercent: 50, color: .green) 
     drawSlice(rect, startPercent: 50, endPercent: 75, color: .red) 
    } 

    private func drawSlice(_ rect: CGRect, startPercent: CGFloat, endPercent: CGFloat, color: UIColor) { 
     let center = CGPoint(x: rect.origin.x + rect.width/2, y: rect.origin.y + rect.height/2) 
     let radius = min(rect.width, rect.height)/2 
     let startAngle = startPercent/100 * CGFloat.pi * 2 - CGFloat.pi 
     let endAngle = endPercent/100 * CGFloat.pi * 2 - CGFloat.pi 
     let path = UIBezierPath() 
     path.move(to: center) 
     path.addArc(withCenter: center, radius: radius, startAngle: startAngle, endAngle: endAngle, clockwise: true) 
     path.close() 
     color.setFill() 
     path.fill() 
    } 
} 

let pieChart = PieChart(frame: CGRect(x: 0.0, y: 0.0, width: 300.0, height: 300.0)) 
pieChart.backgroundColor = UIColor.clear