繁体   English   中英

如何在PictureBox中平移图像

[英]How to pan Image inside PictureBox

我有一个自定义PictureBox ,可以使用MouseWheel事件放大。 现在我想为它添加一个平移功能。 我的意思是当PictureBox处于缩放状态时,如果用户点击并保持点击然后移动鼠标,图像将在图片框内平移。

这是我的代码,但不幸的是它不起作用! 我不知道在哪里看...

private Point _panStartingPoint = Point.Empty;
private bool _panIsActive;

private void CurveBox_MouseDown(object sender, MouseEventArgs e)
{
    if (e.Button == MouseButtons.Left)
    {
        Focus();
        _panIsActive = true;
        _panStartingPoint = e.Location;
    }
}

private void CurveBox_MouseUp(object sender, MouseEventArgs e)
{
    _panIsActive = false;
}

private void CurveBox_MouseLeave(object sender, EventArgs e)
{
    _panIsActive = false;

}

private void CurveBox_MouseMove(object sender, MouseEventArgs e)
{
    if(_panIsActive && IsZoomed)
    {
        var g = CreateGraphics(); //Create graphics from PictureBox

        var nx = _panStartingPoint.X + e.X;
        var ny = _panStartingPoint.Y + e.Y;
        var sourceRectangle = new Rectangle(nx, ny, Image.Width, Image.Height);
        g.DrawImage(Image, nx, ny, sourceRectangle, GraphicsUnit.Pixel);
    }
}

我怀疑MouseMove事件...我不确定此事件中是否发生任何事情和/或nxny确实包含正确的点。

任何帮助/提示都非常适合!

我认为数学是倒退的。 试试这样:

private Point startingPoint = Point.Empty;
private Point movingPoint = Point.Empty;
private bool panning = false;

void pictureBox1_MouseDown(object sender, MouseEventArgs e) {
  panning = true;
  startingPoint = new Point(e.Location.X - movingPoint.X,
                            e.Location.Y - movingPoint.Y);
}

void pictureBox1_MouseUp(object sender, MouseEventArgs e) {
  panning = false;
}

void pictureBox1_MouseMove(object sender, MouseEventArgs e) {
  if (panning) {
    movingPoint = new Point(e.Location.X - startingPoint.X, 
                            e.Location.Y - startingPoint.Y);
    pictureBox1.Invalidate();
  }
}

void pictureBox1_Paint(object sender, PaintEventArgs e) {
  e.Graphics.Clear(Color.White);
  e.Graphics.DrawImage(Image, movingPoint);
}

你没有处理你的图形对象,并且CreateGraphics只是一个临时绘图(最小化会删除它)所以我将绘图代码移动到Paint事件,并且只是在用户平移时失效。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM