c# pictureBox1打开一张图片,并在图片上通过Graphics生成矩形中心点x=200,y=200,w=400,h=400,点击按钮开始画矩形,通过左键调节矩形大小,并显示在picturebox中
时间: 2024-05-07 19:23:51 浏览: 154
你可以使用以下代码实现:
```csharp
public partial class Form1 : Form
{
private Bitmap bmp;
private Graphics g;
private Rectangle rect;
private bool isDrawing = false;
private Point rectStartPoint;
public Form1()
{
InitializeComponent();
bmp = new Bitmap(pictureBox1.Width, pictureBox1.Height);
pictureBox1.Image = bmp;
g = Graphics.FromImage(bmp);
rect = new Rectangle(200, 200, 400, 400);
DrawRectangle();
}
private void DrawRectangle()
{
g.Clear(Color.White);
g.DrawRectangle(Pens.Black, rect);
pictureBox1.Refresh();
}
private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
{
if (rect.Contains(e.Location))
{
isDrawing = true;
rectStartPoint = e.Location;
}
}
private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
{
if (isDrawing)
{
int dx = e.X - rectStartPoint.X;
int dy = e.Y - rectStartPoint.Y;
rect.Width += dx;
rect.Height += dy;
rectStartPoint = e.Location;
DrawRectangle();
}
}
private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
{
isDrawing = false;
}
private void button1_Click(object sender, EventArgs e)
{
DrawRectangle();
}
}
```
这个代码将在PictureBox上绘制一个初始大小为400x400的矩形,并且可以在PictureBox中使用鼠标左键调整矩形大小。当单击按钮时,矩形将被重新绘制。注意,此代码仅处理矩形的大小调整,不处理矩形的移动。
阅读全文