怎么将winform的picturebox中使用g.DrawRectangle画出的矩形四个点坐标保存在text文件中
时间: 2024-05-11 17:14:38 浏览: 17
您可以使用 StreamWriter 类将矩形的四个点坐标保存到文本文件中。具体步骤如下:
1. 在画矩形的方法中,获取矩形的四个点坐标。
例如,使用 Rectangle 类的 Location 和 Size 属性获取矩形的左上角坐标和宽高:
```
Rectangle rect = new Rectangle(10, 10, 50, 50);
int x1 = rect.Location.X;
int y1 = rect.Location.Y;
int x2 = rect.Location.X + rect.Size.Width;
int y2 = rect.Location.Y + rect.Size.Height;
```
2. 创建一个 StreamWriter 对象,打开或创建要保存的文本文件。
例如,使用以下代码创建一个名为“coordinates.txt”的文本文件:
```
StreamWriter writer = new StreamWriter("coordinates.txt");
```
3. 将矩形的四个点坐标写入文本文件中。
例如,使用以下代码将矩形的四个点坐标写入文本文件:
```
writer.WriteLine($"({x1}, {y1})");
writer.WriteLine($"({x2}, {y1})");
writer.WriteLine($"({x2}, {y2})");
writer.WriteLine($"({x1}, {y2})");
```
4. 关闭 StreamWriter 对象。
例如,使用以下代码关闭 StreamWriter 对象:
```
writer.Close();
```
完整示例代码:
```
private void DrawRectangle()
{
Rectangle rect = new Rectangle(10, 10, 50, 50);
int x1 = rect.Location.X;
int y1 = rect.Location.Y;
int x2 = rect.Location.X + rect.Size.Width;
int y2 = rect.Location.Y + rect.Size.Height;
using (Graphics g = pictureBox1.CreateGraphics())
{
g.DrawRectangle(Pens.Black, rect);
}
using (StreamWriter writer = new StreamWriter("coordinates.txt"))
{
writer.WriteLine($"({x1}, {y1})");
writer.WriteLine($"({x2}, {y1})");
writer.WriteLine($"({x2}, {y2})");
writer.WriteLine($"({x1}, {y2})");
}
}
```
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)