Thursday, June 5, 2014
Drawing Rectangular with Mouse
namespace Zau_DrawRectWithMouse
{
public partial class Form1 : Form
{
Bitmap bmap;
Graphics g;
Rectangle rect;
public Form1()
{
InitializeComponent();
// to use the cross "+" cursor
this.Cursor = System.Windows.Forms.Cursors.Cross;
// to reduce flicker
this.DoubleBuffered = true;
bmap = new Bitmap(pictureBox1.Width, pictureBox1.Height);
g = Graphics.FromImage(bmap);
}
private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
{
// "e.X" and "e.Y" are used to get MousePositionX and MousePositionY
rect = new Rectangle(e.X, e.Y, 0, 0);
this.Invalidate();
}
private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
{
// This makes sure that the left mouse button is pressed.
if (e.Button == MouseButtons.Left)
{
// Draws the rectangle as the mouse moves
rect = new Rectangle(rect.Left, rect.Top, e.X - rect.Left, e.Y - rect.Top);
}
this.Invalidate();
}
private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
//using (Pen pen = new Pen(Color.White, 3))
//{
// e.Graphics.DrawRectangle(pen, rect);
// pictureBox1.Image = bmap;
//}
}
private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
Pen pen = new Pen(Color.White, 3);
g.DrawRectangle(pen, rect);
pictureBox1.Image = bmap;
}
}
private void btnClearCanvas_Click(object sender, EventArgs e)
{
bmap = new Bitmap(pictureBox1.Width, pictureBox1.Height);
g = Graphics.FromImage(bmap);
pictureBox1.Image = bmap;
}
}
}
Labels:
C#
Subscribe to:
Post Comments (Atom)

No comments:
Post a Comment