我们在用C# Graphics 画图的时候如何实现通过鼠标滚轮进行图形的放大缩小呢?
首先我们需要了解System.Drawing.Drawing2D命名空间下有个Matrix类, 此类提供了多种图形变换方法.查看微软API, 我们发现方法Scale 只有基于原点进行放大缩小, 没有类似RotateAt的基于某个坐标进行变换.
故,我们可以换种思路. 先缩放, 然后再移动, 从而实现鼠标坐标进行放大缩小的.
重点代码如下
private void Form1_MouseWheel(object sender, MouseEventArgs e)
{
if (e.Delta != 0)
{
if (e.Delta > 0)
{
g.Clear(Color.Black);
System.Drawing.Drawing2D.Matrix myMatrix = new System.Drawing.Drawing2D.Matrix();
myMatrix.Scale(2,2);
myMatrix.Translate(-0.5f * centerP.X, -0.5f * centerP.Y);
gp.Transform(myMatrix);
g.FillPath(new SolidBrush(Color.Red), gp);
}
else
{
System.Drawing.Drawing2D.Matrix myMatrix = new System.Drawing.Drawing2D.Matrix();
myMatrix.Scale(0.5f , 0.5f);
myMatrix.Translate(centerP.X, centerP.Y);
gp.Transform(myMatrix);
g.Clear(Color.Black);
g.FillPath(new SolidBrush(Color.Red), gp);
}
}
}