c#窗体接受视觉信息
时间: 2025-06-14 10:16:40 浏览: 8
### 在 C# WinForms 或 WPF 中实现图像或图形显示
在 C# 开发中,无论是使用 WinForms 还是 WPF,都可以通过不同的方式实现图像或图形的接收与处理。以下是两种框架下实现图像或图形显示的具体方法。
#### 1. 使用 WinForms 显示图像或图形
WinForms 提供了 `PictureBox` 控件用于显示图像。如果需要动态绘制图形,可以使用 `Graphics` 类。以下是一个示例代码,展示如何在 WinForms 中加载并显示图像:
```csharp
using System;
using System.Drawing;
using System.Windows.Forms;
namespace WindowsFormsApplication3
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
// 加载图像到 PictureBox 控件
pictureBox1.Image = Image.FromFile("example.jpg");
}
private void DrawOnForm(PaintEventArgs e)
{
Graphics g = e.Graphics;
Pen pen = new Pen(Color.Red, 2);
// 绘制矩形
g.DrawRectangle(pen, new Rectangle(50, 50, 100, 100));
}
}
}
```
上述代码展示了如何将图像加载到 `PictureBox` 控件中,并通过 `Paint` 事件动态绘制一个矩形[^1]。
#### 2. 使用 WPF 显示图像或图形
WPF 提供了更强大的功能来处理图像和图形,主要通过 XAML 和代码后台结合的方式实现。以下是一个示例代码,展示如何在 WPF 中显示图像以及绘制图形:
```xml
<Window x:Class="WpfApp.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="450" Width="800">
<Grid>
<!-- 显示图像 -->
<Image Source="example.jpg" Stretch="Uniform" Width="200" Height="200"/>
<!-- 绘制图形 -->
<Canvas Width="300" Height="300">
<Rectangle Canvas.Left="50" Canvas.Top="50" Width="100" Height="100" Fill="Red"/>
</Canvas>
</Grid>
</Window>
```
上述代码展示了如何通过 XAML 定义图像控件和图形控件。WPF 的优势在于其灵活性和丰富的样式支持[^3]。
#### 3. 处理视觉信息(如边界框绘制)
如果需要对图像进行处理,例如绘制检测到的对象边界框,可以参考 OpenCVSharp 库。以下是一个简单的函数,展示如何在图像上绘制边界框:
```csharp
using OpenCvSharp;
public void DisplayImageWithPredictions(Mat image, List<(Rect bbox, string label)> predictions)
{
foreach (var (bbox, label) in predictions)
{
Cv2.Rectangle(image, bbox, Scalar.Red, 2);
Cv2.PutText(image, label, new Point(bbox.X, bbox.Y - 10), HersheyFonts.HersheySimplex, 0.9, Scalar.White, 2);
}
Cv2.ImShow("Detection Results", image);
Cv2.WaitKey(0);
}
```
上述代码展示了如何使用 OpenCVSharp 库在图像上绘制边界框并显示结果[^2]。
### 总结
- **WinForms**:适合简单的图像显示和图形绘制任务,主要依赖 `PictureBox` 和 `Graphics`。
- **WPF**:提供更灵活的图像和图形处理能力,尤其适合需要复杂视觉效果的应用场景。
- 如果需要高级图像处理功能,建议结合第三方库(如 OpenCVSharp)实现更复杂的操作。
阅读全文
相关推荐


















