在图片框中移动图像

本文关键字:移动 图像 | 更新日期: 2023-09-27 18:37:28

我在互联网上尝试了一些例子,但那些尝试过的人都失败了。我在运行时携带一个图像,它运行良好,但是我无法移动加载到图片框中的图像,

遵循代码:

public partial class imagem : Form { private CarregaDados parent = null; int width; int height;
    public imagem()
    {
        InitializeComponent();
    }       
    /// <summary>
    /// Cria uma referencia entre os form
    /// Assim conseguimos controlar os elementos do outro form
    /// </summary>
    /// <param name="_parent"></param>
    public imagem(CarregaDados _parent)
    {
      this.parent = _parent;
    }
    public void CarregaImagem(string caminho)
    {
        Image image =  Image.FromFile(caminho);            
        //valores da largura  e altura
        int width = image.Width;
        int height = image.Height;
        //verificar a largura
        //e o pixel em que deve comecar a imagem
        Rectangle rect = new Rectangle(0, 0, width, height);
        imagemPictureBox.Image = image;
    }
    //Primeiro ponto na imagem carregada
    private Point firstPoint = new Point();
    private int x = 0;
    private int y = 0;        
    private void imagemPictureBox_MouseDown(object sender, MouseEventArgs e)
    {
        x = e.X;
        y = e.Y;        
    }
    private void imagemPictureBox_MouseMove(object sender, MouseEventArgs e)
    {
        if (e.Button == MouseButtons.Left)
        {
            imagemPictureBox.Left = (imagemPictureBox.Left + e.X) - x;
            imagemPictureBox.Top = (imagemPictureBox.Top + e.Y) - y;
        }
    }
    private void imagemPictureBox_MouseUp(object sender, MouseEventArgs e)
    {
        if (e.Button == MouseButtons.Left)
        {
            imagemPictureBox.Left = x;
            imagemPictureBox.Top = y;
        }
    }

}

我把图片框放在面板中。我无法移动图像,有人可以告诉我出了什么问题

在图片框中移动图像

将这些添加到设计器中

this.imagemPictureBox.MouseMove += new System.Windows.Forms.MouseEventHandler(this.imagemPictureBox_MouseMove);
this.imagemPictureBox.MouseUp += new System.Windows.Forms.MouseEventHandler(this.imagemPictureBox_MouseUp);
this.imagemPictureBox.MouseDown += new System.Windows.Forms.MouseEventHandler(this.imagemPictureBox_MouseDown);