jingwood / d2dlib

A .NET library for hardware-accelerated, high performance, immediate mode rendering via Direct2D.
MIT License
245 stars 43 forks source link

Draw Pie Chart? #33

Closed CBergAccount closed 3 years ago

CBergAccount commented 4 years ago

Hi!

I have tried to figure a way to draw a PIE Chart but without success. Could anyone help to point me in a direction of how to do that? Would like to fill the pie charts, not just draw the line.

Thanks... Christian

jingwood commented 4 years ago

I have added a demo to draw a pie chart. Hope it helps you.

image

You can find the demo program from the Examples project of source code.

And this library has been updated for the feature to draw pie geometry, please use the latest code or latest NuGet package 1.2.2. Here is the full example code:

public partial class PieChart : DemoForm
{
    List<PieInfo> pies = new List<PieInfo>();

    protected override void OnLoad(EventArgs e)
    {
        base.OnLoad(e);

        Text = "PieChart Demo";
        CreateChart();
    }

    void CreateChart()
    {
        pies.Clear();

        // define the figure origin and size
        var figureOrigin = new D2DPoint(300, 300);
        var figureSize = new D2DSize(300, 300);

        var records = new float[] { .6f, .3f, .1f };

        float currentAngle = 0;

        // create pie geometries from records
        foreach (var record in records)
        {
            var angleSpan = record * 360;

            var path = Device.CreatePieGeometry(figureOrigin, figureSize, currentAngle, currentAngle + angleSpan);
            pies.Add(new PieInfo { path = path, color = D2DColor.Randomly() });

            currentAngle += angleSpan;
        }

        Invalidate();
    }

    protected override void OnRender(D2DGraphics g)
    {
        base.OnRender(g);

        // draw background
        g.FillRectangle(100, 100, 400, 400, D2DColor.LightYellow);

        // draw pie geometries
        foreach (var pie in pies)
        {
            g.FillPath(pie.path, pie.color);
            g.DrawPath(pie.path, D2DColor.LightYellow, 2);
        }

        g.DrawText("Click to change color", D2DColor.Black, 250, 550);
    }

    protected override void OnMouseUp(MouseEventArgs e)
    {
        base.OnMouseUp(e);
        CreateChart();
    }
}

class PieInfo
{
    public D2DGeometry path;
    public D2DColor color;
}

The point is the new added method Device.CreatePieGeometry, you can simply call this method to create a pie geometry by the following parameters.

image

Once you have a pie geometry you can draw or fill by following code:

g.FillPath(geometry, color);     // fill
g.DrawPath(geometry, color, 2);    // stroke