gpt4 book ai didi

c# - 从鼠标移动事件调用绘画事件

转载 作者:太空狗 更新时间:2023-10-30 01:21:23 25 4
gpt4 key购买 nike

当鼠标移到 panel2 上时,我需要画线。到目前为止,我已经完成了以下操作

public Form1()
{
InitializeComponent();

}

private void panel2_Paint(object sender, PaintEventArgs e)
{
if (isDragging)
{
letsPaint(sender, e);
}
}

private void panel2_MouseMove(object sender, MouseEventArgs e)
{
if (isDragging)
{
mouseMoveX = e.X;
mouseMoveY = e.Y;
this.Paint += new PaintEventHandler(panel2_Paint);
}
}

private void letsPaint(object sender, PaintEventArgs e)
{
Pen blackpen = new Pen(Color.Black, 3);
Graphics g = e.Graphics;
g.DrawLine(blackpen, mouseClickedX, mouseClickedY, mouseMoveX, mouseMoveY);
g.Dispose();
}

但是当我移动鼠标时没有任何反应。我想我在这里做错了 PaintEventHandler() 。请告诉我该怎么做,以及是否有更好的方法。

此外,我认为我的方法会在表单上画线,但我需要在 panel2 上画线。怎么做?提前致谢。

最佳答案

你使:

public Form1()
{
InitializeComponent();
panel2.Paint += new letsPaint;
}

private void panel2_MouseMove(object sender, MouseEventArgs e)
{
if (isDragging) {
mouseMoveX = e.X;
mouseMoveY = e.Y;
panel2.Invalidate();
}
}

并且您没有处理图形对象(您没有创建它),但是您处理了笔:

private void letsPaint(object sender, PaintEventArgs e) {             
using (Pen blackpen = new Pen(Color.Black, 3)) {
e.Graphics.DrawLine(blackpen,
mouseClickedX, mouseClickedY, mouseMoveX, mouseMoveY);
}
}

这是一个快速处理位图的小方法:

Bitmap bmp;
Point lastPoint;

public Form1() {
InitializeComponent();
bmp = new Bitmap(panel1.ClientSize.Width, panel1.ClientSize.Height,
System.Drawing.Imaging.PixelFormat.Format32bppPArgb);

panel1.MouseDown += panel1_MouseDown;
panel1.MouseMove += panel1_MouseMove;
panel1.Paint += panel1_Paint;
}

void panel1_Paint(object sender, PaintEventArgs e) {
e.Graphics.DrawImage(bmp, Point.Empty);
}

void panel1_MouseMove(object sender, MouseEventArgs e) {
if (e.Button == MouseButtons.Left) {
using (Graphics g = Graphics.FromImage(bmp)) {
g.DrawLine(Pens.Black, lastPoint, e.Location);
}
lastPoint = e.Location;
panel1.Invalidate();
}
}

void panel1_MouseDown(object sender, MouseEventArgs e) {
lastPoint = e.Location;
}

这会闪烁,因此您需要用双缓冲面板替换您的面板。像这样:

public class PanelEx : Panel {
public PanelEx() {
this.DoubleBuffered = true;
}
}

关于c# - 从鼠标移动事件调用绘画事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15843357/

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