设计Windows应用程序:利用PictureBox控件设计一个图片查看器,观看图片及图片放大、缩小,还原比例的效果并显示代码
时间: 2024-02-21 12:00:37 浏览: 133
以下是一个简单的C#代码示例,可以通过PictureBox控件实现图片的查看、缩放、还原功能:
```csharp
public partial class Form1 : Form
{
private Image originalImage;
private float zoomFactor = 1.0f;
public Form1()
{
InitializeComponent();
}
private void openToolStripMenuItem_Click(object sender, EventArgs e)
{
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.Filter = "Image Files (*.bmp;*.jpg;*.jpeg,*.png)|*.BMP;*.JPG;*.JPEG;*.PNG";
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
originalImage = Image.FromFile(openFileDialog.FileName);
pictureBox1.Image = originalImage;
pictureBox1.SizeMode = PictureBoxSizeMode.Zoom;
zoomFactor = 1.0f;
}
}
private void zoomInToolStripMenuItem_Click(object sender, EventArgs e)
{
zoomFactor += 0.1f;
pictureBox1.Width = (int)(originalImage.Width * zoomFactor);
pictureBox1.Height = (int)(originalImage.Height * zoomFactor);
}
private void zoomOutToolStripMenuItem_Click(object sender, EventArgs e)
{
zoomFactor -= 0.1f;
pictureBox1.Width = (int)(originalImage.Width * zoomFactor);
pictureBox1.Height = (int)(originalImage.Height * zoomFactor);
}
private void actualSizeToolStripMenuItem_Click(object sender, EventArgs e)
{
zoomFactor = 1.0f;
pictureBox1.Width = originalImage.Width;
pictureBox1.Height = originalImage.Height;
}
}
```
在这个示例中,我们使用了一个OpenFileDialog控件来打开图像文件,将打开的图像文件赋值给PictureBox控件的Image属性,通过设置SizeMode为Zoom来自适应显示图片,实现了缩放功能。同时,我们还为菜单栏的缩放功能提供了事件处理程序,以及还原功能。由于PictureBox控件的Width和Height属性的值为整型,因此我们需要将缩放比例转换为浮点型,并将缩放后的值进行取整。
阅读全文