在pictureBox画矩形可用mouse调节大小、拖动位置
时间: 2023-06-26 10:08:18 浏览: 93
c#在pictureBox控件上绘制矩形框,鼠标点击可拖拽,伸缩
4星 · 用户满意度95%
好的,您可以通过以下代码实现该功能:
```csharp
public partial class Form1 : Form
{
private bool isMouseDown = false;
private Point mouseDownPos;
private Rectangle rectangle = new Rectangle(50, 50, 100, 100);
public Form1()
{
InitializeComponent();
pictureBox1.MouseDown += pictureBox1_MouseDown;
pictureBox1.MouseMove += pictureBox1_MouseMove;
pictureBox1.MouseUp += pictureBox1_MouseUp;
pictureBox1.Paint += pictureBox1_Paint;
}
private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
isMouseDown = true;
mouseDownPos = e.Location;
}
}
private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
{
if (isMouseDown)
{
int width = e.X - mouseDownPos.X;
int height = e.Y - mouseDownPos.Y;
rectangle = new Rectangle(mouseDownPos.X, mouseDownPos.Y, width, height);
pictureBox1.Invalidate();
}
}
private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
isMouseDown = false;
}
}
private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
e.Graphics.DrawRectangle(Pens.Red, rectangle);
}
}
```
在上述代码中,我们通过 `pictureBox1` 控件的 `MouseDown`、`MouseMove` 和 `MouseUp` 事件来实现鼠标的拖动功能,同时通过 `pictureBox1` 控件的 `Paint` 事件在控件上绘制矩形。其中, `isMouseDown` 变量用于判断鼠标是否按下, `mouseDownPos` 变量用于记录鼠标按下的位置, `rectangle` 变量用于存储矩形的位置和大小信息。您可以根据需要修改矩形的初始位置和大小。
阅读全文