日期:2014-05-20 浏览次数:20941 次
public partial class PainterForm : Form { private Color color = Color .Black ; int size = 4; Point startpoint; Image orginalImg;//原始图像 Image finishingImg;//中间图像 public Bitmap bitmap; private string sType = "Pencil"; bool shouldPaint = false; public PainterForm() { InitializeComponent(); bitmap = new Bitmap(pictureBox1.Width, pictureBox1.Height); Graphics g = Graphics.FromImage(bitmap); g.FillRectangle(new SolidBrush(pictureBox1.BackColor), new Rectangle(0, 0, pictureBox1.Width, pictureBox1.Height)); g.Dispose(); orginalImg = (Image)bitmap.Clone(); finishingImg = (Image)bitmap.Clone(); } private void pictureBox1_MouseDown(object sender, MouseEventArgs e) { shouldPaint = true; startpoint = new Point(e.X, e.Y); } private void pictureBox1_MouseUp(object sender, MouseEventArgs e) { shouldPaint = false; orginalImg = finishingImg; } private void pictureBox1_MouseMove(object sender, MouseEventArgs e) { Graphics graphics = pictureBox1.CreateGraphics(); Image img = (Image)orginalImg.Clone(); if (shouldPaint && sType !="Pencil" && sType !="Eraser" ) { Graphics g = Graphics.FromImage(img); switch (sType) { case "Line": { g.DrawLine(new Pen(color , size), startpoint , new Point(e.X, e.Y)); break; } case "Rect": { float width = Math.Abs(e.X - startpoint.X);//确定矩形的宽 float heigth = Math.Abs(e.Y - startpoint.Y);//确定矩形的高 PointF rectStartPoint = startpoint; if (e.X < startpoint.X) rectStartPoint.X = e.X; if (e.Y < startpoint.Y) rectStartPoint.Y = e.Y; g.DrawRectangle(new Pen(color ,size), rectStartPoint.X, rectStartPoint.Y, width, heigth); break; } case "Circle": { Point Cir = startpoint ; if (e.X < startpoint.X) Cir.X = e.X; if (e.Y < startpoint.Y) Cir.Y = e.Y; g.DrawEllipse(new Pen(color, size), Cir.X, Cir.Y, Math.Abs(e.X - startpoint.X), Math.Abs(e.Y - startpoint.Y)); break; } g.Dispose(); finishingImg = (Image)img.Clone(); //this.pictureBox.CreateGraphics().DrawImage(img, 0, 0); graphics.DrawImage(finishingImg , 0, 0); img.Dispose(); } } g.Dispose(); graphics.DrawImage(finishingImg , 0, 0); } } private void pictureBox1_Paint(object sender, PaintEventArgs e) { Graphics gra = pictureBox1.CreateGraphics(); gra .DrawImage(bitmap , 0, 0); }