C#使用Winform 写一个 读取展示图片的范例,该范例中的图片控件需要支持放大缩小及画图文字功能
时间: 2024-10-23 17:16:49 浏览: 5
在C# Winform中,你可以使用PictureBox控件来显示和操作图片,并结合Zooming和Drawing功能。以下是一个基本的范例,展示了如何做到这一点:
```csharp
using System;
using System.Drawing;
using System.Windows.Forms;
public partial class MainForm : Form
{
private PictureBox pictureBox1;
private bool isZoomed = false;
public MainForm()
{
InitializeComponent();
// 初始化PictureBox
pictureBox1 = new PictureBox();
pictureBox1.Dock = DockStyle.Fill;
pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage; // 初始设置成填充模式
Controls.Add(pictureBox1);
// 加载图片并设置鼠标滚轮事件处理图片缩放
pictureBox1.ImageLocation = "path_to_your_image.jpg";
pictureBox1.MouseWheel += pictureBox_MouseWheel;
}
private void pictureBox_MouseWheel(object sender, MouseEventArgs e)
{
if (isZoomed)
UnzoomPictureBox();
else
ZoomPictureBox(e.Delta > 0); // 滚轮向上放大,向下缩小
}
private void ZoomPictureBox(bool zoomIn)
{
isZoomed = true;
int zoomFactor = 1.2f; // 缩放因子
if (zoomIn)
{
Size newSize = pictureBox1.Size * zoomFactor;
pictureBox1.Size = newSize;
pictureBox1.Location = new Point((pictureBox1.Width - newSize.Width) / 2, (pictureBox1.Height - newSize.Height) / 2);
}
else
{
pictureBox1.Size = pictureBox1.PreviousSize; // 如果已经放大,则恢复原尺寸
}
}
private void UnzoomPictureBox()
{
isZoomed = false;
pictureBox1.Size = pictureBox1.PreviousSize; // 回到原始大小
}
// 添加一个用于画图的文字功能,例如使用Pen和Graphics对象
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
using (var pen = new Pen(Color.Black, 2))
{
// 示例:在图片中心绘制一条线
int centerX = pictureBox1.ClientSize.Width / 2;
int centerY = pictureBox1.ClientSize.Height / 2;
e.Graphics.DrawLine(pen, centerX, 0, centerX, pictureBox1.ClientSize.Height);
}
}
}
阅读全文