【问题标题】:Issue with Picturebox and trying to update imagesPicturebox 出现问题并尝试更新图像
【发布时间】:2020-04-19 21:40:59
【问题描述】:

我正在尝试更新计时器上图片框中的图像。老实说,我在图片框方面没有太多经验,而且从我完成任何 C# 工作以来已经有大约 5 年的时间了。我试图在谷歌和这里搜索,似乎找不到我认为我需要的答案:/

基本上,这就是我想要做的。表单需要以秒为单位的时间(例如 5 秒), 当一个按钮被点击时,一个新的表单被打开。这个新表单上有一个图片框,它将显示目录中的随机照片。我可以让图片框显示随机照片,但是当我尝试在不重新打开表单的情况下刷新它时,这就是我遇到问题的地方。

我有一个变量 (timeVar) 设置为以秒为单位的输入时间,并且在后台有一个计时器,每次计时器滴答时,它都会通过减去 1 来更新 timerVar。这就是我必须在图片中设置的图片每次迭代的框。有一个外循环遍历我的列表(dirList),直到它命中列表中的每个项目。

    while(timerVar > 0)
{
     pictureTimer.Start();
     imagePathPic = imagePath + dirList[ind];
     sessionPicture.ImageLocation = @imagePathPic;
     sessionPicture.Refresh();
}
    pictureTimer.Stop();
    timeVar = 5;

dirList 是给定目录中所有图像的列表,imagePath 是保存目录的字符串。我的列表/字符串的功能以及外部循环都已成功测试,但是当我在上面的循环中应用图片框时,它不会做任何事情,直到它获得最后一张图片然后显示。为了在表格上显示每张图片,我缺少什么?如果您需要更多信息,请告诉我。

谢谢!

【问题讨论】:

  • 删除循环。需要使用Timer.Tick事件来改变Image(Tick事件属于System.Windows.Forms.Timer组件)。

标签: c# visual-studio-2019 picturebox


【解决方案1】:

对我来说,它可以从文件加载图像。 Image.FromFile() 在 System.Drawing 命名空间下。我不必添加任何Refresh() 方法。您可以尝试在您的用户表单上调用 Refresh this.Refresh(),或者直接调用 Refresh()。

public partial class Form1 : Form
{
    Timer _timer = new Timer();
    string[] _images;
    Random _random = new Random();
    string _imagesFolder = @"C:\Users\Me\Desktop\Picures\";
    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        _timer.Tick += new EventHandler(timer_Tick);
        _timer.Interval = 2000;
        _images = Directory.GetFiles(_imagesFolder);
    }
    private void button1_Click(object sender, EventArgs e)
    {
        _timer.Enabled = !_timer.Enabled;
    }

    private void timer_Tick(object sender, EventArgs e)
    {
        var index = _random.Next(0, _images.Length);
        var imagePath = Path.Combine(_imagesFolder, _images[index]);
        pictureBox1.Image = Image.FromFile(imagePath);
    }
}

这是样机:

【讨论】:

  • pictureBox1.Image?.Dispose(); pictureBox1.Image = Image.FromFile(imagePath);
  • 我像上面的示例一样修改了我的代码,除了没有使用按钮启用计时器,我在表单加载方法中启用它,因为我需要它在表单加载时启动。表单运行但没有图片加载。
  • pictureTimer.Tick += new EventHandler(pictureTimer_Tick);图片Timer.Interval = 5000; _images = Directory.GetFiles(_imagesFolder); pictureTimer.Enabled = true;
  • 嗨@user2921015,我将启用计时器移至Form1_Load() 方法,它正在工作。当您在pictureTimer_Tick() 上设置断点时,您的计时器是否在计时? _images 数组是否包含任何元素? pictureBox1.Visible 是否设置为 true?
  • 没关系。我只是将相同的图像加载到图像对象中并将图片框的大小调整为该图像的宽度/高度。再次感谢!
猜你喜欢
  • 2021-04-19
  • 1970-01-01
  • 2016-11-10
  • 2021-09-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多