Search code examples
c#sizemschart

How to set the size of MS chart in millimetre instead of pixel in C#


I am trying to set the size of chart object in millimetre in C# using the following code:

var chart = new Chart();
chart.RenderingDpiX = 300;
chart.RenderingDpiY = 300;
chart.CreateGraphics().PageUnit = GraphicsUnit.Millimeter;
chart.Size = new Size(290, 200); // meant to be 290 millimetre not pixel
...
chart.SaveImage(@"D:\Temp\tttt.png", ChartImageFormat.Png);

I expect that size of saved image be something around 290 * (300/254) = 3425 pixel, whereas the size of image is 290 pixel by 200 pixel?

I also tried to set the page unit in postPaint event using

private void ChartPostPaint(object sender, ChartPaintEventArgs e)
{
  var g = e.ChartGraphics.Graphics;
  g.PageUnit = GraphicsUnit.Millimeter;
} 

But this does not work either! Could you please help me how to set the size of chart in millimetre or inches instead of pixel?


Solution

  • From the documentation of Chart() seems that the default measurement unit is px.
    But, you could use the px as an input for a method which could give you the value on mm.
    To do so you could write:

    private double toMM(int _px)
    {
        return this._px*(300/254);
    }
    

    So, now you would have something like:

    chart.Size = new Size(toMM(290), toMM(200));