【发布时间】:2010-08-18 19:49:23
【问题描述】:
我正在尝试在 WinForms 中实现一个简单的“缩放至点”功能。当鼠标在同一点并且鼠标滚轮滚入/滚出时,效果很好。当鼠标位置在滚动之间改变时,它会跳到那个位置并且非常不稳定。这是您可以添加到Form 进行测试的控件代码:
public class Canvas : Control
{
private Bitmap Image;
private TextureBrush ImageBrush;
private Point Origin;
private Matrix TransformMatrix;
public float ZoomScale
{
get;
set;
}
public Canvas()
{
this.SetStyle(ControlStyles.ResizeRedraw | ControlStyles.OptimizedDoubleBuffer, true);
this.Image = // Load your picture here.
this.ImageBrush = new TextureBrush(this.Image, WrapMode.Clamp);
this.ZoomScale = 1.0f;
this.TransformMatrix = new Matrix();
}
protected override void OnPaint(PaintEventArgs e)
{
float zs = this.ZoomScale;
var matrix = this.TransformMatrix.Clone();
e.Graphics.Transform = matrix;
var c = e.ClipRectangle;
// Transform the clip rectangle, is this even right?
var x = (int)Math.Round(c.X / zs - matrix.OffsetX / zs);
var y = (int)Math.Round(c.Y / zs - matrix.OffsetY / zs);
var w = (int)Math.Round(c.Width / zs);
var h = (int)Math.Round(c.Height / zs);
// Draw the image scaled and translated.
e.Graphics.FillRectangle(this.ImageBrush, x, y, w - 1, h - 1);
}
protected override void OnMouseWheel(MouseEventArgs e)
{
if (e.Delta > 0)
{
this.ZoomScale += 0.1f;
}
else
{
this.ZoomScale -= 0.1f;
}
this.ZoomToPoint(e.Location);
this.Refresh();
}
private void ZoomToPoint(Point origin)
{
this.Origin = origin;
float zoomScale = this.ZoomScale;
// The important part.
var matrix = new Matrix(1, 0, 0, 1, 0, 0);
matrix.Reset();
matrix.Translate(-origin.X, -origin.Y, MatrixOrder.Append);
matrix.Scale(zoomScale, zoomScale, MatrixOrder.Append);
matrix.Translate(origin.X, origin.Y, MatrixOrder.Append);
this.TransformMatrix = matrix;
}
protected override void OnResize(EventArgs e)
{
base.OnResize(e);
this.ZoomToPoint(this.Origin);
}
}
所以重要的部分显然是affine transformation。我知道它在 Adobe Flex 中,但我从 this website 得到了 Translate、Scale、Translate 的想法(我正在尝试做的很好的例子)。在我尝试之前,我没有意识到MatrixOrder.Append 是.NET 中的关键。但问题仍然存在。尝试在 WinForms 应用程序中加载控件,您就会明白我的意思。有谁知道这是什么问题?
编辑:我需要手动计算矩形的原因是因为我要绘制更多而不仅仅是图像。这是一个像 Visio 一样执行的画布。我还需要一种方法来转换特定的Point。
EDIT 2:我知道我可以在Matrix 上使用Invert() 然后TransformPoints() 来获得适当的转换点,但它仍然不能解决鼠标不稳定的问题移动。我正在考虑从图像上角的位置计算Origin,但它不起作用。
【问题讨论】: