图片picturebox放大缩小,拖拽,限制位置,c#
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace wenqihzi
{
class mouse_events
{
public static void pb_add_equal_events(PictureBox pictureBox)
{
pictureBox.MouseDown += mouse_down;
pictureBox.MouseMove += mouse_move;
pictureBox.MouseUp += mouse_up;
pictureBox.MouseWheel += pb_wheel;
}
public static Point bmove = Point.Empty;
public static void mouse_up(object sender, MouseEventArgs e)
{
bmove = Point.Empty;
}
public static void mouse_down(object sender, MouseEventArgs e)
{
bmove = new Point(Cursor.Position.X, Cursor.Position.Y);
//if (e.Button == MouseButtons.Right)
//{
// Bitmap myBitmap = Win32APICall.GetDesktop();
// Color myColor = myBitmap.GetPixel(MousePosition.X, MousePosition.Y);
// double dmax_min = (double)nud_max_wld.Value - (double)nud_min_wld.Value;
// double dmin = (double)nud_min_wld.Value;
// double value = get_value_by_color(myColor, dmax_min, dmin);
// tb_show_information.AppendText("当前数据是:" + value + "\r\n");
//}
}
public static void mouse_move(object sender, MouseEventArgs e)
{
if (bmove != Point.Empty)
{
int i = Cursor.Position.X - bmove.X;
int j = Cursor.Position.Y - bmove.Y;
Point location = new Point();
location.X = ((PictureBox)sender).Location.X + i;
location.Y = ((PictureBox)sender).Location.Y + j;
int w = ((PictureBox)sender).Width-10;
int h = ((PictureBox)sender).Height-10;
if (location.X < -w)
{
location.X = -w;
}
if (location.Y < -h)
{
location.Y = -h;
}
if (location.X >w)
{
location.X = w;
}
if (location.Y >h )
{
location.Y = h;
}
((PictureBox)sender).Location = location;
bmove = new Point(Cursor.Position.X, Cursor.Position.Y);
}
}
//private void PictureBox2_MouseWheel(object sender, MouseEventArgs e)
//{
// pb_wheel( (sender), e);
//}
//private void PictureBox1_MouseWheel(object sender, MouseEventArgs e)
//{
// pb_wheel( (sender), e);
//}
public static void pb_wheel(object sender, MouseEventArgs e)
{
PictureBox pictureBox = (PictureBox)(sender);
if (pictureBox.Width < 100)
{
return;
}
double x = (double)e.X / pictureBox.Width;
double y = (double)e.Y / pictureBox.Height;
//int i = Cursor.Position.X;
//int j = Cursor.Position.Y;
var p = pictureBox.Size;
p.Width += e.Delta;
p.Height += e.Delta * pictureBox.Height / pictureBox.Width;
if (p.Height < 100)
{
return;
}
if (p.Height > 5000)
{
return;
}
pictureBox.Size = p;
double x2 = (double)e.X / pictureBox.Width;
double y2 = (double)e.Y / pictureBox.Height;
double x3 = x2 - x;
double y3 = y2 - y;
int x4 = (int)(pictureBox.Width * x3);
int y4 = (int)(pictureBox.Height * y3);
Point location = new Point();
location.X = pictureBox.Location.X + x4;
location.Y = pictureBox.Location.Y + y4;
pictureBox.Location = location;
}
}
}