110,567
社区成员
发帖
与我相关
我的任务
分享
private Point P3, P4;//定义两个点(启点,终点)
private static bool drawing = false;//设置一个启动标志
private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
{
P3 = new Point(e.X, e.Y);
P4 = new Point(e.X, e.Y);
drawing = true;
}
private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
{
Graphics g = pictureBox1.CreateGraphics();
//Graphics g = Graphics.FromImage(this.pictureBox1.Image);
if (e.Button == MouseButtons.Left)
{
if (drawing)
{
//drawing = true;
Point currentPoint = new Point(e.X, e.Y);
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;//消除锯齿
g.DrawLine(new Pen(Color.Blue, 2), P4, currentPoint);
P4.X = currentPoint.X;
P4.Y = currentPoint.Y;
}
}
}
private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
{
drawing = false;
}
private void button5_Click(object sender, EventArgs e)
{
pictureBox1.Image.Save(@"D:\2.jpg", ImageFormat.Jpeg);
MessageBox.Show("ok");
}
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
this.pictureBox1.Paint += pictureBox1_Paint; // 可以移动到设计器生成代码里
}
private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
{
currentScribble = new List<Point>();
currentScribble.Add(e.Location);
}
private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left && this.currentScribble != null)
{
currentScribble.Add(e.Location);
RedrawPictureBox();
}
}
List<Point> currentScribble = null;
List<Point[]> scribbles = new List<Point[]>();
void pictureBox1_Paint(object sender, PaintEventArgs e)
{
using (Pen pen = new Pen(Color.Blue, 2))
{
foreach (Point[] points in scribbles)
{
e.Graphics.DrawLines(pen, points);
}
if (this.currentScribble != null)
{
e.Graphics.DrawLines(pen, this.currentScribble.ToArray());
}
}
}
private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
{
if (currentScribble != null && currentScribble.Count > 1)
{
RedrawPictureBox();
this.scribbles.Add(currentScribble.ToArray());
}
this.currentScribble = null;
}
private void RedrawPictureBox()
{
if (currentScribble.Count >= 2)
{
Rectangle last = new Rectangle(currentScribble[currentScribble.Count - 2], Size.Empty);
Rectangle current = new Rectangle(currentScribble[currentScribble.Count - 1], Size.Empty);
Rectangle invalidateArea = Rectangle.Inflate(Rectangle.Union(last, current), 2, 2);
this.pictureBox1.Invalidate(invalidateArea);
}
}
private void button5_Click(object sender, EventArgs e)
{
Rectangle rect = new Rectangle(Point.Empty, this.pictureBox1.Size);
using (Bitmap bmp = new Bitmap(rect.Width, rect.Height))
{
this.pictureBox1.DrawToBitmap(bmp, rect); // 画pictureBox1显示的图,假定它没有边框
using (Graphics g = Graphics.FromImage(bmp))
{
pictureBox1_Paint(this, new PaintEventArgs(g, rect)); // 画自定义标记
}
bmp.Save(@"D:\2.jpg", ImageFormat.Jpeg);
}
MessageBox.Show("ok");
}
}