gpt4 book ai didi

c# - 在 C# 中拖放矩形

转载 作者:行者123 更新时间:2023-12-03 08:07:31 25 4
gpt4 key购买 nike

我想知道如何在 C# 中绘制矩形并将其拖放到页面中,这里是我绘制它的代码,但我无法拖放它。

public partial class Form1 : Form
{
public bool drag = false;
int cur_x, cur_y;
Rectangle rec = new Rectangle(10, 10, 100, 100);
public Form1()
{
InitializeComponent();
}

protected override void OnPaint(PaintEventArgs r)
{
base.OnPaint(r);
Graphics g = r.Graphics;
//g.DrawRectangle(Pens.Black, rec);
g.FillRectangle(Brushes.Aquamarine, rec);

}
private void recmousedown(object sender, MouseEventArgs m)
{
if (m.Button != MouseButtons.Left)
return;
rec = new Rectangle(m.X, m.Y,100,100);

drag = true;
cur_x = m.X;
cur_y = m.Y;
}

private void recmousemove(object sender, MouseEventArgs m)
{
if (m.Button != MouseButtons.Left)
return;

rec.X = m.X;
rec.Y = m.Y;
Invalidate();
}
}

最佳答案

你已经很接近了,你只需要更好地初始化矩形并在 Move 事件中调整矩形大小:

  public partial class Form1 : Form {
public Form1() {
InitializeComponent();
this.DoubleBuffered = true;
}
Rectangle rec = new Rectangle(0, 0, 0, 0);

protected override void OnPaint(PaintEventArgs e) {
e.Graphics.FillRectangle(Brushes.Aquamarine, rec);
}
protected override void OnMouseDown(MouseEventArgs e) {
if (e.Button == MouseButtons.Left) {
rec = new Rectangle(e.X, e.Y, 0, 0);
Invalidate();
}
}
protected override void OnMouseMove(MouseEventArgs e) {
if (e.Button == MouseButtons.Left) {
rec.Width = e.X - rec.X;
rec.Height = e.Y - rec.Y;
Invalidate();
}
}
}

关于c# - 在 C# 中拖放矩形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2442105/

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