I need to extract a custom shape from a given image. That custom shape can be, for example, a triangle.

For example, if source picture is 100px width and 100px heigth, I need to define a triangle with points:
(x=0 y=0) , (x = 50, y = 50), (x = 0, y = 50)

I have found many examples for extracting a rectangle and also a circle, but I need to define, by declaring manually its points, a custom shape.

Any idea?

Thanks in advance

Recommended Answers

All 2 Replies

If you want to draw an image cliped to a triangle then you need to use a GraphicsPath to set a clip Region.
The following code clips the Bitmap1.bmp image when drawn at the top left of the form.

private void Form1_Paint(object sender, PaintEventArgs e)
            // create a graphic path to hold the shape data
            System.Drawing.Drawing2D.GraphicsPath path = new System.Drawing.Drawing2D.GraphicsPath();
            // add a set of points that define the shape
            path.AddLines(new Point[] { new Point(0, 0), new Point(50, 0), new Point(50, 50) });
            // close the shape
            // set the clop region of the forms graphic object to be the new shape
            e.Graphics.Clip = new Region(path);
            // draw the image cliped to the custom shape
            e.Graphics.DrawImage(Image.FromFile("Bitmap1.bmp"), new Point(0, 0));

Nice answer, nick.crane!

In order to draw over a PictureBox instead of the Form, I just need to add something like this:

Graphics graph = myPictureBox.CreateGraphics();

Thanks again!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.