【问题标题】:How to set Background of a Button without flicker?如何设置按钮的背景而不闪烁?
【发布时间】:2013-01-09 00:50:36
【问题描述】:

我正在尝试将按钮的背景更改为图像源。当我们导航到页面时,我想将该图像加载到内存中,以便它在第一次显示时不会闪烁。

在 Windows Phone 上,我能够这样创建图像源:

  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;

我在我的 Windows 8 应用商店应用中尝试了类似的方法:

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

但同样的问题也会发生。该按钮已经具有作为背景的不同图像,并且在某个事件中我希望它更改为新背景。但是当我更改源时,会观察到明显的闪烁。我假设这是因为图像尚未在内存中,因为第二次修改图像源时问题就消失了。

有人知道解决方案吗?我需要以某种方式强制加载此图像。

谢谢!

【问题讨论】:

    标签: xaml windows-8 windows-runtime


    【解决方案1】:

    如果您在 BitmapImage 上使用 SetSourceAsync 方法并在将其附加到图像源之前等待它,您应该不会看到闪烁:-

    // 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;
    }
    

    MSDN 文档对此有更多信息

    【讨论】:

    • 谢谢罗斯。你确定这是资源位图的好主意吗?我只是担心我会绕过为资源提供的自动位图缓存,特别是因为我将有十几个按钮使用相同的位图。
    【解决方案2】:

    谢谢罗斯,但我最终做的是通过使用与上面类似的代码预加载了我需要的半打左右的位图,当然除了资源。我在页面加载时异步执行此操作,然后在按钮背景上设置 ImageSource 时,我使用了已经预加载的位图。这样我就知道我没有为位图的每个 instance 分配新的内存块。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-08-30
      • 2012-12-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多