我一直在研究 System.Drawing
,除了一件事,我已经按照我希望的方式工作了。当我松开鼠标按钮时,这条线就消失了。
如何确保线条准确地保持在我离开的位置?
using System;
using System.Drawing;
using System.Windows.Forms;
namespace DrawingSample
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
this.DoubleBuffered = true;
}
Graphics graphics;
Random
color = new Random(1);
Int32
penThickness = 1;
Point
currentCursorLocation, initialTouchLocation, touchOffset;
Boolean
mouseDown;
protected override void OnPaint(PaintEventArgs e)
{
graphics = e.Graphics;
if (mouseDown)
{
graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
//DrawRectangle(graphics);
//DrawEllipse(graphics);
DrawLine(graphics);
}
}
private void DrawRectangle(Graphics graphics)
{
graphics.DrawRectangle(new Pen(
Color.FromArgb((color.Next(1,
255)),
(color.Next(1,
255)),
(color.Next(1,
255)))
,
penThickness),
currentCursorLocation.X,
currentCursorLocation.Y,
(this.Width / 2),
(this.Height / 2)
);
}
private void DrawEllipse(Graphics graphics)
{
graphics.DrawEllipse(new Pen(
Color.FromArgb((color.Next(1, 255)),
(color.Next(1, 255)),
(color.Next(1, 255))), penThickness),
new RectangleF(currentCursorLocation, new Size(100, 100)));
}
private void DrawLine(Graphics graphics)
{
graphics.DrawLine(new Pen(
Color.FromArgb((color.Next(1, 255)),
(color.Next(1, 255)),
(color.Next(1, 255))), penThickness),
currentCursorLocation.X,
currentCursorLocation.Y,
touchOffset.X,
touchOffset.Y
);
}
private void Form1_MouseMove(object sender, MouseEventArgs e)
{
currentCursorLocation = e.Location;
this.Refresh();
}
private void Form1_MouseDown(object sender, MouseEventArgs e)
{
if (!mouseDown)
{
touchOffset = e.Location;
mouseDown = true;
}
}
private void Form1_MouseUp(object sender, MouseEventArgs e)
{
mouseDown = false;
}
}
}
最佳答案
您要求代码表现得像那样。所以它做同样的事情。
您在 Form1_MouseUp
事件中将 mouseDown
设置为 false。
private void Form1_MouseUp(object sender, MouseEventArgs e)
{
mouseDown = false; //<--Here
}
然后你在绘制线条之前检查 if (mouseDown)
。
protected override void OnPaint(PaintEventArgs e)
{
graphics = e.Graphics;
if (mouseDown)//<--Here
{
graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
//DrawRectangle(graphics);
//DrawEllipse(graphics);
DrawLine(graphics);
}
}
我猜你不需要 if (mouseDown)
检查 OnPaint
方法。
不确定您的意图是什么,如果您需要更多帮助,请在答案下方发表评论。
关于c# - 为什么释放鼠标按钮时绘制的线会消失?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25379383/