public partial class Form4 : Form
{
#region 成员变量
Point m_p1, m_p2;
bool m_flgKeuDowm = false;
Bitmap m_mapStart;
Bitmap m_mapEnd;
Bitmap m_mapInit;
Graphics m_graphics;
#endregion
public Form4()
{
InitializeComponent();
m_graphics = pictureBox1.CreateGraphics();
//Image image = Image.FromFile(@"d:\mjy\Led.jpg");
//Bitmap bitmap = new Bitmap(image);
//pictureBox1.Image = bitmap;
// 最初的背景图存起来,清除绘制图形时用
m_mapInit = (Bitmap)pictureBox1.BackgroundImage;
}
private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
{
m_flgKeuDowm = true;
_initPoint(e);
}
private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
{
m_flgKeuDowm = false;
// 最终的图片设为背景图
pictureBox1.BackgroundImage = m_mapEnd;
// 起止点初始化
_initPoint(e);
}
private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
{
if (!m_flgKeuDowm)
{
return;
}
else
{
m_p2 = new Point(e.X, e.Y);
}
int width = Math.Abs(e.X - m_p1.X);
int height = Math.Abs(e.Y - m_p1.Y);
_draw();
}
private void _draw()
{
// 每次的【终止图】都是取自【起始图】
m_mapEnd = (Bitmap)m_mapStart.Clone();
Graphics g = Graphics.FromImage(m_mapEnd);
Pen pen = new Pen(Color.Red, 3);
if (rdoRect.Checked)
{
Point p1, p2;
_swapPoint(out p1, out p2);
int width = Math.Abs(p2.X - p1.X);
int height = Math.Abs(p2.Y - p1.Y);
g.DrawRectangle(pen, p1.X, p1.Y, width, height);
}
else if (rdoLine.Checked)
{
// 画直线不用转换点坐标,直接用成员变量的Point
g.DrawLine(pen, m_p1, m_p2);
}
m_graphics.DrawImage(m_mapEnd, new Point(0, 0));
}
private void _initPoint(MouseEventArgs e)
{
m_p1 = new Point(e.X, e.Y);
m_p2 = m_p1;
if (pictureBox1.BackgroundImage != null)
{
m_mapStart = (Bitmap)pictureBox1.BackgroundImage;
}
}
private void _printPoint(Point p)
{
Console.WriteLine(p.X + "," + p.Y);
}
private void _swapPoint(out Point _p1, out Point _p2)
{
//实现画框随意翻转
_p1 = m_p1;
_p2 = m_p2;
if (m_p1.X > m_p2.X)
{
int tmp = _p1.X;
_p1.X = _p2.X;
_p2.X = tmp;
}
if (m_p1.Y > m_p2.Y)
{
int tmp = _p1.Y;
_p1.Y = _p2.Y;
_p2.Y = tmp;
}
}
private void btnSave_Click(object sender, EventArgs e)
{
// 保存
SaveFileDialog dlg = new SaveFileDialog();
dlg.DefaultExt = "png";
dlg.Filter = "Png Files|*.png";
dlg.FileName = "截图";
DialogResult dlgRet = dlg.ShowDialog();
if (dlgRet == DialogResult.OK)
{
pictureBox1.BackgroundImage.Save(dlg.FileName, System.Drawing.Imaging.ImageFormat.Png);
}
}
private void btnClear_Click(object sender, EventArgs e)
{
pictureBox1.BackgroundImage = m_mapInit;
}
}