using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Reflection; using System.Text; using System.Windows.Forms; namespace Lskj.Control { public partial class PictureBoxEx : BaseUserControl { private static bool isMove = false; private static Point mouseDownPoint; private static int zoomStep = 70; public static int ZoomStep { get { return zoomStep; } set { zoomStep = value; } } public Image Image { get { return this.mainPicBox.Image; } set { this.mainPicBox.Image = value; } } public PictureBoxEx() { InitializeComponent(); this.mainPicBox.MouseWheel += PictureBoxEx_MouseWheel; this.mainPicBox.MouseDown += MainPicBox_MouseDown; this.mainPicBox.MouseMove += MainPicBox_MouseMove; this.mainPicBox.MouseUp += MainPicBox_MouseUp; this.SizeChanged += PictureBoxEx_SizeChanged; } private void MainPicBox_MouseUp(object sender, MouseEventArgs e) { if (e.Button == MouseButtons.Left) { isMove = false; } } private void MainPicBox_MouseMove(object sender, MouseEventArgs e) { PictureBox pbox = sender as PictureBox; pbox.Focus(); //鼠标在picturebox上时才有焦点,此时可以缩放 if (isMove) { int x, y; //新的pictureBox1.Location(x,y) int moveX, moveY; //X方向,Y方向移动大小。 moveX = Cursor.Position.X - mouseDownPoint.X; moveY = Cursor.Position.Y - mouseDownPoint.Y; x = pbox.Location.X + moveX; y = pbox.Location.Y + moveY; pbox.Location = new Point(x, y); mouseDownPoint.X = Cursor.Position.X; mouseDownPoint.Y = Cursor.Position.Y; } } private void MainPicBox_MouseDown(object sender, MouseEventArgs e) { PictureBox pbox = sender as PictureBox; if (e.Button == MouseButtons.Left) { mouseDownPoint.X = Cursor.Position.X; //记录鼠标左键按下时位置 mouseDownPoint.Y = Cursor.Position.Y; isMove = true; pbox.Focus(); //鼠标滚轮事件(缩放时)需要picturebox有焦点 } } private void PictureBoxEx_SizeChanged(object sender, EventArgs e) { this.mainPicBox.Width = this.Width; this.mainPicBox.Height = this.Height; } private void PictureBoxEx_MouseWheel(object sender, MouseEventArgs e) { PictureBox pbox = sender as PictureBox; int x = e.Location.X; int y = e.Location.Y; int ow = pbox.Width; int oh = pbox.Height; int VX, VY; //因缩放产生的位移矢量 if (e.Delta > 0) //放大 { pbox.Width += ZoomStep; pbox.Height += ZoomStep; PropertyInfo pInfo = pbox.GetType().GetProperty("ImageRectangle", BindingFlags.Instance | BindingFlags.NonPublic); Rectangle rect = (Rectangle)pInfo.GetValue(pbox, null); pbox.Width = rect.Width; pbox.Height = rect.Height; } if (e.Delta < 0) //缩小 { //防止一直缩成负值 if (pbox.Width < 300) return; pbox.Width -= ZoomStep; pbox.Height -= ZoomStep; PropertyInfo pInfo = pbox.GetType().GetProperty("ImageRectangle", BindingFlags.Instance | BindingFlags.NonPublic); Rectangle rect = (Rectangle)pInfo.GetValue(pbox, null); pbox.Width = rect.Width; pbox.Height = rect.Height; } VX = (int)((double)x * (ow - pbox.Width) / ow); VY = (int)((double)y * (oh - pbox.Height) / oh); pbox.Location = new Point(pbox.Location.X + VX, pbox.Location.Y + VY); } } }