位图图像未更改c#



在我的wpf项目中有一个区域应该通过链接显示图像。链接上的图像以一定的频率变化。我的代码:

string path1 = @"";//link from image
image_1.Source = null;
GC.Collect();
BitmapImage bi1 = new BitmapImage();
bi1.BeginInit();
bi1.CacheOption = BitmapCacheOption.OnLoad;
bi1.UriSource = new Uri(path1);
bi1.EndInit();
bi1.Freeze();
image_1.Source = bi1;
GC.Collect();
delete_old(path1);//delete file

这一切都发生在一个循环中,在image_1.Source = null和赋一个新值之间的那一刻,图像消失了一段时间,这看起来很糟糕。

我想让图片从旧的变成新的,没有黑屏,我没有找到其他的方法来实现。如果我不将路径设置为null,那么图像就不会改变。

不确定"干净的架构";解决方案,但有一个变通方法,你可以使用。您可以创建2个Image控件,并在每次迭代中切换它们。

一开始你将有两个控件,一个可见,一个不可见:

<Grid>
<Image x:Name="image_1" Stretch="Uniform" />
<Image x:Name="image_2" Stretch="Uniform" Visibility="Collapsed" />
</Grid>

现在你可以修改你的代码,通过更新它的Visibility来切换控件:

private Image _currentImage;
private Image _bufferImage;
public YourControlConstructor()
{
InitializeComponent();
// initialize a variables with Image controls
_currentImage = image_1;
_bufferImage = image_2;
}
private void UpdateImage(string path)
{
_bufferImage.Source = null;
GC.Collect();
BitmapImage bi = new BitmapImage();
bi.BeginInit();
bi.CacheOption = BitmapCacheOption.OnLoad;
bi.UriSource = new Uri(path);
bi.EndInit();
bi.Freeze();
_bufferImage.Source = bi;
// exchange variables to know which image is currently displayed
Image temp = _currentImage;
_currentImage = _bufferImage;
_bufferImage = temp;
// Update visibility to change images
_currentImage.Visibility = Visibility.Visible;
_bufferImage.Visibility = Visibility.Collapsed;
GC.Collect();
delete_old(path);
}

最新更新