@SARATH 提供的答案因复制和粘贴而略有改动,但并未产生预期的结果。
将 _degrees 更改为 _percentComplete
通过为 percentComplete 添加参数并为 _backColor 和 _frontColor 添加缺少的成员变量赋值,修复了用于更改颜色的重载构造函数
为绘制一个完整的圆添加了常量浮点值(FULL_CIRCLE)
将 _percentComplete 乘以 FULL_CIRCLE 以获得两条弧的结束角度(具有不同方向)
半径的计算
public class CircleGraph : UIView
{
const float FULL_CIRCLE = 2 * (float)Math.PI;
int _radius = 10;
int _lineWidth = 10;
nfloat _percentComplete = 0.0f;
UIColor _backColor = UIColor.LightGray; //UIColor.FromRGB(46, 60, 76);
UIColor _frontColor = UIColor.Green; //UIColor.FromRGB(234, 105, 92);
public CircleGraph(CGRect frame, int lineWidth, nfloat percentComplete)
{
_lineWidth = lineWidth;
_percentComplete = percentComplete;
this.Frame = new CGRect(frame.X, frame.Y, frame.Width, frame.Height);
this.BackgroundColor = UIColor.Clear;
}
public CircleGraph(CGRect frame, int lineWidth, nfloat percentComplete, UIColor backColor, UIColor frontColor)
{
_lineWidth = lineWidth;
_percentComplete = percentComplete;
this.Frame = new CGRect(frame.X, frame.Y, frame.Width, frame.Height);
this.BackgroundColor = UIColor.Clear;
_backColor = backColor;
_frontColor = frontColor;
}
public override void Draw(CoreGraphics.CGRect rect)
{
base.Draw(rect);
using (CGContext g = UIGraphics.GetCurrentContext())
{
var diameter = Math.Min(this.Bounds.Width, this.Bounds.Height);
_radius = (int)(diameter / 2) - _lineWidth;
DrawGraph(g, this.Bounds.GetMidX(), this.Bounds.GetMidY());
};
}
public void DrawGraph(CGContext g, nfloat x, nfloat y)
{
g.SetLineWidth(_lineWidth);
// Draw background circle
CGPath path = new CGPath();
_backColor.SetStroke();
path.AddArc(x, y, _radius, 0, _percentComplete * FULL_CIRCLE, true);
g.AddPath(path);
g.DrawPath(CGPathDrawingMode.Stroke);
// Draw overlay circle
var pathStatus = new CGPath();
_frontColor.SetStroke();
// Same Arc params except direction so colors don't overlap
pathStatus.AddArc(x, y, _radius, 0, _percentComplete * FULL_CIRCLE, false);
g.AddPath(pathStatus);
g.DrawPath(CGPathDrawingMode.Stroke);
}
}
示例
var circleGraph = new CircleGraph(circleGraphView.Frame, 20, 0.75f);
CircleGraph 为 75%