我有一个C#窗口表单,用于导入和显示多个图像。
我可以导入多个图像并显示第一张图像,但在逐个显示图像时出现了一些问题。
程序流程:用户单击按钮,然后选择多个图像。之后,第一张图像应显示在图片框上。当用户单击“下一个图像按钮”时,应显示下一个图像。
第一张图片能够在图片框上显示,但不知道逐一显示它们。 是否有任何配置来实现此目的或如何通过编码实现它。 谢谢大家。
我的编码:
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
InitializeOpenFileDialog();
}
private void InitializeOpenFileDialog()
{
// Set the file dialog to filter for graphics files.
this.openFileDialog1.Filter =
"Images (*.BMP;*.JPG;*.GIF)|*.BMP;*.JPG;*.GIF|" +
"All files (*.*)|*.*";
// Allow the user to select multiple images.
this.openFileDialog1.Multiselect = true;
this.openFileDialog1.Title = "My Image Browser";
}
private void SelectFileButton_Click(object sender, EventArgs e)
{
DialogResult dr = this.openFileDialog1.ShowDialog();
if (dr == System.Windows.Forms.DialogResult.OK)
{
// Read the files
foreach (String file in openFileDialog1.FileNames)
{
// Create a PictureBox.
PictureBox pb = new PictureBox();
Image loadedImage = Image.FromFile(file);
pb.Height = loadedImage.Height;
pb.Width = loadedImage.Width;
pb.Image = loadedImage;
flowLayoutPanel1.Controls.Add(pb);
}
}
}
}
答案 0 :(得分:3)
您不必为每个图片添加PictureBox
控件,它会使您的表单重载。
我的建议是保留所有已加载图像的列表,以及当前显示图像的索引器。
<强>代码:强>
在表单中添加PictureBox
(让我们称之为pictureBox1
),您希望在其中显示图片。
此外,将这些属性添加到您的班级:
private List<Image> loadedImages = new List<Image>();
private int currentImageIndex;
在“加载图片”按钮中点击事件:
private void SelectFileButton_Click(object sender, EventArgs e)
{
DialogResult dr = this.openFileDialog1.ShowDialog();
if (dr == System.Windows.Forms.DialogResult.OK)
{
loadedImages.Clear();
// Read the files
foreach (String file in openFileDialog1.FileNames)
{
// Create a PictureBox.
loadedImages.Add(Image.FromFile(file));
}
if (loadedImages.Count > 0)
{
currentImageIndex = 0;
pictureBox1.Image= loadedImages[currentImageIndex];
}
}
}
最后,对于下一个/上一个按钮单击事件,您可以添加以下代码:
// Mod function to support negative values (for the back button).
int mod(int a, int b)
{
return (a % b + b) % b;
}
// Show the next picture in the PictureBox.
private void button_next_Click(object sender, EventArgs e)
{
currentImageIndex = mod(currentImageIndex + 1, loadedImages.Count);
pictureBox1.Image = loadedImages[currentImageIndex];
}
// Show the previous picture in the PictureBox.
private void button_prev_Click(object sender, EventArgs e)
{
currentImageIndex = mod(currentImageIndex - 1, loadedImages.Count);
pictureBox1.Image = loadedImages[currentImageIndex];
}