Search code examples
c#winformsvisual-studio-2019

Filling / Transforming polygon correctly in c#


I have following polygon marked:

enter image description here

I need to fill the inside of the polygon correctly.

Using following code:

using (SolidBrush br = new SolidBrush(Color.FromArgb(100, Color.Yellow)))
{
   e.Graphics.FillPolygon(br, points);
}

Where points is System.Drawing.Point[] points = new System.Drawing.Point[total_points_size];

Above points array will contain multiple Point(s) with there X,Y respectively. You can see the blue ellipsis in image.

Following are the co-ordinates:

enter image description here

I get following result:

enter image description here

I just need the polygon to be filled from inside, looks like due to some reason the markup is going to (0,0) for each point, how can we fix this ?

I have learned the solution might involve graphics transform with offset, but I'm not able to figure out exact solution.


Solution

  • Here is the supposedly equivalent code to plot your polygon. I tested it with both Net7 and NET 4.7.2.

    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            this.Paint += Form1_Paint;
        }
    
        private static readonly Point[] points = new[]
        {
            new Point(62, 478),
            new Point(333, 411),
            new Point(411, 392),
            new Point(650, 454),
            new Point(784, 467),
            new Point(1105, 529),
            new Point(1136, 574),
            new Point(1182, 580),
            new Point(1247, 689),
            new Point(24, 693),
        };
    
        private void Form1_Paint(object sender, PaintEventArgs e)
        {
            using (Graphics g = this.CreateGraphics())
            using (SolidBrush br = new SolidBrush(Color.FromArgb(100, Color.Yellow)))
            {
                g.FillPolygon(br, points);
            }
        }
    
    }
    

    Here is the graphic result. enter image description here