鼠标画出矩形
public partial class ImageLoader : Form
{
private Point startPoint, endPoint;
bool mark = false;
Graphics bitG;
Bitmap bits;
public ImageLoader()
{
InitializeComponent();
picBox1.Dock = DockStyle.Fill;
bits = new Bitmap(picBox1.Width, picBox1.Height);
bitG = Graphics.FromImage(bits);
bitG.Clear(Color.White);
picBox1.Image = bits;
picBox1.MouseDown += new MouseEventHandler(picBox1_MouseDown);
picBox1.MouseMove += new MouseEventHandler(picBox1_MouseMove);
picBox1.MouseUp += new MouseEventHandler(picBox1_MouseUp);
}
public Rectangle MakeRectangle(Point p1, Point p2)
{
int top, left, bottom, right;
top = p1.X <= p2.X ? p1.X : p2.X;
left = p1.Y <= p2.Y ? p1.Y : p2.Y;
bottom = p1.X > p2.X ? p1.X : p2.X;
right = p1.Y > p2.Y ? p1.Y : p2.Y;
return (new Rectangle(top, left, bottom - top, right - left));
}
private void picBox1_MouseUp(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
Pen pen1 = new Pen(Color.Black, 1);
endPoint = e.Location;
Rectangle ret1 = MakeRectangle(startPoint, endPoint);
bitG.DrawRectangle(pen1, ret1);
picBox1.Image = bits;
mark = false;
}
}
private void picBox1_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
mark = true;
startPoint = e.Location;
endPoint = e.Location;
}
}
private void picBox1_MouseMove(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left && mark)
{
Rectangle ret = MakeRectangle(startPoint, endPoint);
ret.Width += 2;
ret.Height += 2;
picBox1.Invalidate(ret);
picBox1.Update();
Graphics g = picBox1.CreateGraphics();
Pen pen = new Pen(Color.Black, 1);
endPoint = e.Location;
ret = MakeRectangle(startPoint, endPoint);
g.DrawRectangle(pen, ret);
}
}
private void picBox1_Paint(object sender, PaintEventArgs e)
{
}
}