使用GDI+在屏幕上绘制一幅图片,并支持鼠标移动。
使用picture控件很容易,GDI+也和控件一样的原理:
窗体初始化时记录图片左上角点坐标(全局私有变量),鼠标Down时记录起始的鼠标坐标,然后再鼠标Up时,用图片原来的左上角点坐标加上当前鼠标位置,然后再减去Down时的鼠标位置,即得到新的图片左上角点位置。
-------------------------------------------------------------------
private Image bmp;
private int x, y;
private Point[] bmpBounds;
private Point orgPoint;
private Rectangle bmpRect;
public Form1()
{
InitializeComponent();
bmp = Image.FromFile("1.jpeg");
x = 0;
y = 0;
bmpBounds = new Point[3];
bmpBounds[0] = new Point(x, y);
bmpRect = new Rectangle(x,y,bmp.Width ,bmp.Height );
}
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
Graphics g = e.Graphics;
g.ScaleTransform(1.0f, 1.0f);
g.DrawImage(bmp,bmpRect );
g.Dispose();
}
private void Form1_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
orgPoint = new Point(e.X, e.Y);
}
}
private void Form1_MouseUp(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
bmpBounds[0].X = bmpBounds[0].X + e.X - orgPoint.X;
bmpBounds[0].Y = bmpBounds[0].Y + e.Y - orgPoint.Y;
bmpRect = new Rectangle(bmpBounds[0].X, bmpBounds[0].Y, bmp.Width, bmp.Height);
this.Invalidate();
}
}
--------------------------------------------------------------------
如果使用picturebox控件的话,将Down事件换为Move事件效果似乎更好。