GDI+ 图片移动问题
我刚使用GDI+不久,现在在图片移动上遇到如下困惑,一整天了,没找到原因。采用的是pictureBox显示,首先将一幅背景图和一幅小图画到对象bmp中,然后显示在pictureBox1上。当鼠标拖动图片的的时候判断拖得是大图还是小图,拖大图就一起移动,拖小图就小图移动。现在载入图片后直接拖小图没有问题,但是拖完大图再拖小图坐标系统就出问题了。由于对GDI+刚开始学习,所以想不通错误的地方。高手们帮看看代码有什么问题?谢谢!以下是测试主要代码(只是为了测试功能):
public partial class Form1 : Form
{
private Bitmap bmp = null;
private Bitmap bmt = null;
private Bitmap bmk = null;
private Point lastPoint = new Point(); //点击位置
private Point offset = new Point();//最终位置
int i = 150, k = 0;
Rectangle r = new Rectangle(150, 0, 65,82);//直接将小图初始位置标出
private void Form1_Load(object sender, EventArgs e)
{
SetStyle(ControlStyles.DoubleBuffer, true);
SetStyle(ControlStyles.AllPaintingInWmPaint, true);
SetStyle(ControlStyles.UserPaint, true);
bmp = new Bitmap(pictureBox1.Width,pictureBox1.Height);
}
private void btNew_Click(object sender, EventArgs e)
{
Graphics g1 = Graphics.FromImage(bmp);
Bitmap bmtest = new Bitmap(@"2.jpg");
bmk = new Bitmap(bmtest);
bmtest.SetResolution(128f, 128f);
g1.DrawImage(bmtest, 0, 0);
bmtest.Dispose();
bmtest = new Bitmap(@"1.jpg");
bmt = new Bitmap(bmtest);
g1.DrawImage(bmtest, 150, 0);
pictureBox1.Invalidate();
}
private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
{
lastPoint = e.Location;
}
private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
{
Graphics g1 = Graphics.FromImage(bmp);
PointTextBox.Text = e.Location.X.ToString() + "," + e.Location.Y.ToString() + "|" + r.X.ToString() + "," + r.Y.ToString();
if (e.Button == MouseButtons.Left)
{
Cursor.Current = Cursors.Hand;
if (r.Contains(lastPoint))
{
r.Offset((e.X - lastPoint.X), (e.Y - lastPoint.Y));
g1.DrawImage(bmt,r);
}
else
{
offset.X += e.X - lastPoint.X;
offset.Y += e.Y - lastPoint.Y;
r.Offset((e.X - lastPoint.X), (e.Y - lastPoint.Y));
}
lastPoint = e.Location;
pictureBox1.Invalidate();
}
}
private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
if (bmp != null)
{
//e.Graphics.DrawImage(bmp, pictureBox1.ClientRectangle, -offset.X, -offset.Y, pictureBox1.ClientSize.Width, pictureBox1.ClientSize.Height, GraphicsUnit.Pixel);
e.Graphics.DrawImage(bmp, offset);
}
}