Apply ScaleTransform to Graphics GDI+

2019-07-03 11:54发布

I have put this simple code together to draw a line. Now I want to apply a ScaleTransform to it by a factor of 10; but the code below doesn't work.

var bitmap = new Bitmap(pictureBox1.Size.Width, pictureBox1.Size.Height);
var g = Graphics.FromImage(bitmap);
pictureBox1.Image = bitmap;

var pn = new Pen(Color.Wheat, -1);
g.DrawLine(pn, 0, 0, 10, 10);

pn.Dispose();

// I'm trying to scaletransform here!
g.ScaleTransform(10, 10);

Update:

What is the correct way to update the changes? I'm not getting any results from this :(

g.ScaleTransform(1, 1);
pictureBox1.Invalidate();

1条回答
可以哭但决不认输i
2楼-- · 2019-07-03 12:31

You must apply the transformation BEFORE drawing the line!

var g = Graphics.FromImage(bitmap);
g.ScaleTransform(10, 10);    
using (pn = new Pen(Color.Wheat, -1)) {
    g.DrawLine(pn, 0, 0, 10, 10);
}

Transformations are applied to the transformation matrix of the graphics object (g.Transform).

Also make use of the using statement in order to dispose the resources. It will even dispose the pen if an exception should occur or if the using statement-block should be left with a return or break statement.

查看更多
登录 后发表回答