簡體   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