-1

I have an area in my wpf project that should display an image by link. The image on the link changes with a certain frequency. My code:

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

This all happens in a loop and in the moment between image_1.Source = null and assigning a new value, the image disappears for a while, which looks terrible.

I would like the picture to change from the old to the new one without a blank screen, I did not find other ways to implement it. If I don't set the path to null, then the image just doesn't change.

2
  • create 2 Image controls and switch between them every time you change a picture. or just delete a string where you set souce to null Commented Apr 5, 2023 at 8:28
  • If i delete string with sourse = null then image wasn't changing. Only the first image will be shown Commented Apr 5, 2023 at 8:32

1 Answer 1

0

Not sure about "clean architecture" solution but there is a workaround that you can use. You can create a 2 Image controls and switch them per each iteration.

At the start you will have 2 controls one visible and one not:

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

Now you can modify your code to switch between controls by updating its 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);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.