gpt4 book ai didi

c# - 在窗体上绘制一条连续的线,例如 Winforms C# 上的 MS paint

转载 作者:行者123 更新时间:2023-11-30 22:00:23 26 4
gpt4 key购买 nike

我有一个关于 Graphics 对象的问题。我想像 MS paint 一样画一条连续的线。我不知道如何实现这样的事情。我知道如何从鼠标位置开始一行。这是我在图片框上做的并添加新的点(e.X,e.Y)。当然,另一条线不能相同,否则将看不到任何线。我无法制作另一个 Point(10, 10) 或类似的东西。因为这样它会始终从同一点创建一条线。

有谁知道如何画连续的线(带曲线)

与mouse_down和mouse_up事件有关系吗?我真的被这个问题困扰了很长时间。如果你们中的任何人有时间向我解释可行的方法,那就太好了!

提前致谢!

最佳答案

我刚刚为您实现了简单的绘画。只需创建一个新项目并将下面的代码复制到 Form1.cs 文件。代码中的注释应该解释它是如何工作的。

public partial class Form1 : Form
{
private Bitmap bmp; // Place to store our drawings
private List<Point> points; // Points of currently drawing line
private Pen pen; // Pen we will use to draw

public Form1()
{
InitializeComponent();
DoubleBuffered = true; // To avoid flickering effect

bmp = new Bitmap(640, 480); // This is our canvas that will store drawn lines
using (Graphics g = Graphics.FromImage(bmp))
g.Clear(Color.White); // Let's make it white, like paper

points = new List<Point>(); // Here we will remember the whole path
pen = new Pen(Color.Black);

MouseDown += OnMouseDown; // Start drawing
MouseMove += OnMouseMove; // Drawing...
MouseUp += OnMouseUp; // Stop drawing
Paint += OnPaint; // Show the drawing
}

void OnPaint(object sender, PaintEventArgs e)
{
e.Graphics.DrawImage(bmp, 0, 0); // Show what is drawn
if (points.Count > 0)
e.Graphics.DrawLines(pen, points.ToArray()); // Show what is currently being drawn
}

void OnMouseDown(object sender, MouseEventArgs e)
{
if (e.Button != MouseButtons.Left)
return;

points.Clear();
points.Add(e.Location); // Remember the first point
}

void OnMouseMove(object sender, MouseEventArgs e)
{
if (e.Button != MouseButtons.Left)
return;

points.Add(e.Location); // Add points to path
Invalidate(); // Force to repaint
}

void OnMouseUp(object sender, MouseEventArgs e)
{
if (e.Button != MouseButtons.Left)
return;

SaveToBitmap(); // Save the drawn line to bitmap
points.Clear(); // Our drawing is saved, we can clear the list of points
}

private void SaveToBitmap()
{
if (points.Count == 0)
return;

using (Graphics g = Graphics.FromImage(bmp))
g.DrawLines(pen, points.ToArray()); // Just draw current line on bitmap
}
}

结果:
enter image description here

关于c# - 在窗体上绘制一条连续的线,例如 Winforms C# 上的 MS paint,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28650588/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com