How to set Background of a Button without flicker?

2019-08-10 11:25发布

I am trying to change the Background of a button to an image source. I want to load that image in memory when we navigate to the page so that it doesn't flicker the first time it shows.

On Windows Phone, I was able to create the image source as such:

  StreamResourceInfo resourceInfo = Application.GetResourceStream(uri);
  BitmapImage bitmapSource = new BitmapImage();

  // Avoid flicker by not delay-loading.
  bitmapSource.CreateOptions = BitmapCreateOptions.None;

  bitmapSource.SetSource(resourceInfo.Stream);

  imageSource = bitmapSource;

I tried something similar in my Windows 8 Store app:

  BitmapImage bitmapSource = new BitmapImage();
  bitmapSource.CreateOptions = BitmapCreateOptions.None;
  bitmapSource.UriSource = uri;
  imageSource = bitmapSource;

but the same problem occurs. The button already has a different image as the Background, and on a certain event I would like it to change to the new background. But when I change the source, a noticeable flicker is observed. I'm assuming this is because the image is not yet in memory, as the issue goes away the second time the image source is modified.

Anyone know a solution? I need to somehow force the loading of this image.

Thanks!

2条回答
来,给爷笑一个
2楼-- · 2019-08-10 12:01

Thanks Ross, but what I ended up doing instead is I preloaded the half dozen or so bitmaps I needed by using similar code to what you had above, except from resource of course. I did this asynchronously when the page loaded, and then when I set the ImageSource on the button background, I used the already preloaded bitmaps. That way I know I'm not allocated a new chunk of memory for every instance of the bitmap.

查看更多
老娘就宠你
3楼-- · 2019-08-10 12:12

If you use the SetSourceAsync method on the BitmapImage and await it before you attach it to the image source you should not see the flicker:-

// Ensure the stream is disposed once the image is loaded
using (IRandomAccessStream fileStream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read))
{
    // Set the image source to the selected bitmap
    BitmapImage bitmapImage = new BitmapImage();
    await bitmapImage.SetSourceAsync(fileStream);
    imageSource  = bitmapImage;
}

The MSDN docs have some more info on this

查看更多
登录 后发表回答