How to set Background of a Button without flicker?

送分小仙女□ 提交于 2019-12-11 10:08:09

问题


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!


回答1:


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




回答2:


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.



来源:https://stackoverflow.com/questions/14226634/how-to-set-background-of-a-button-without-flicker

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!