gpt4 book ai didi

c# - 如何使用 MouseMove 事件绘制单线

转载 作者:行者123 更新时间:2023-11-30 14:41:50 25 4
gpt4 key购买 nike

我正在尝试使用 OnMouseMove() 事件绘制一条直线。我的问题是每次我移动鼠标时它都会留下痕迹。我尝试使用刷新方法,但是当我停止移动鼠标时,该行就消失了。我不想画线OnPaint();,只想画线OnMouseMove()

编辑: 我使用的是透明面板(cp.ExStyle |= 0x20;),所以我不能使用 graphics.Clear()背景颜色()

这是一个没有 Refresh() 的示例图像:

alt text

这是我的代码:

private void panel1_MouseMove(object sender, MouseEventArgs e)
{
Graphics g = panel1.CreateGraphics();

g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
using (var p = new Pen(Color.Black, 3))
{
p.StartCap = System.Drawing.Drawing2D.LineCap.ArrowAnchor;
p.EndCap = System.Drawing.Drawing2D.LineCap.ArrowAnchor;

g.DrawLine(p, st, e.Location);
}
Thread.Sleep(30);
Invalidate();
//this.Refresh();

g.Dispose();
}

问候

最佳答案

以下对我有用。基本上跟踪最后绘制的线条并使用面板的背景颜色绘制它(给出清除它的效果)。

   public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private const int PEN_WIDTH = 3;
private const LineCap START_CAP = LineCap.ArrowAnchor;
private const LineCap END_CAP = LineCap.ArrowAnchor;
Point mAnchorPoint = new Point(10, 10);
Point mPreviousPoint = Point.Empty;

private void panel1_MouseMove(object sender, MouseEventArgs e)
{
using (Graphics g = panel1.CreateGraphics())
{
// Clear last line drawn
using (Pen clear_pen = new Pen(panel1.BackColor, PEN_WIDTH))
{
clear_pen.StartCap = START_CAP;
clear_pen.EndCap = END_CAP;
g.DrawLine(clear_pen, mAnchorPoint, mPreviousPoint);
}

// Update previous point
mPreviousPoint = e.Location;

// Draw the new line
using (Pen draw_pen = new Pen(Color.Black, PEN_WIDTH))
{
draw_pen.StartCap = START_CAP;
draw_pen.EndCap = END_CAP;
g.DrawLine(draw_pen, mAnchorPoint, e.Location);
}
}
}
}

如果面板的背景颜色设置为透明,则需要将 panel1.BackColor 更改为 panel1.Parent.BackColor

如果透明面板不起作用,您可以使用 DrawReversibleLine 函数(虽然这不允许更改线条的颜色或粗细,但绘图应该没有问题/即使面板是透明的也删除:

  Point mAnchorPoint = new Point(200, 200);
Point mPreviousPoint = Point.Empty;

private void panel1_MouseMove(object sender, MouseEventArgs e)
{
if (mPreviousPoint != Point.Empty)
{
// Clear last line drawn
ControlPaint.DrawReversibleLine(PointToScreen(mAnchorPoint), PointToScreen(mPreviousPoint), Color.Pink);
}

// Update previous point
mPreviousPoint = e.Location;
mPreviousPoint.Offset(myPanel1.Location);

// Draw the new line
ControlPaint.DrawReversibleLine(PointToScreen(mAnchorPoint), PointToScreen(mPreviousPoint), Color.Pink);
}

关于c# - 如何使用 MouseMove 事件绘制单线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3714146/

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