My problem is with clipping an image via GraphicsPath. I have a fairly complex clipping path (composed of various arcs) and I need to save only that part of the image that is within this path.
I have a class like this:
class A
{
private GraphicsPath GetGraphicsPath()
{
... some stuff ...
return gp;
}
public void Draw(Graphics g)
{
g.DrawPath(pen, GetGraphicsPath());
}
public Save(Image img, string fileName)
{
Bitmap b = new Bitmap(img.Width, img.Height);
Graphics bg = Graphics.FromImage(b);
bg.Clip = new Region(GetGraphicsPath());
bg.DrawImage(img, 0, 0);
b.Save(fileName + ".png");
}
}
and then I have a form with a panel pnMain, with a background image. I have two buttons with the following functions:
private void button1_Click(object sender, EventArgs e)
{
Graphics g = pnMain.CreateGraphics();
a.Draw(g);
}
private void button2_Click(object sender, EventArgs e)
{
Image img = pnMain.BackgroundImage;
a.Save(img, "test");
}
(in both cases a is an instance of A). My problem is that the clipping region drawn on screen (using first button and method Draw) is what I would like to save, however, the clipped image saved through second button and method Save is distorted, smaller and shifted. What am I missing?
I figured it out — it is the resolution of the background image in the panel. The properties HorizontalResolution and VerticalResolution of the Bitmap img have to match the DPIX and DPIY properties of the Graphics. I did not found out how to set any of these via C#, but I was able to change the resolution of the bitmap in Photoshop and now everything works.