wpf - 提高将大图像放到画布上的速度

时间:2015-12-02 17:48:34

标签: c# wpf canvas

有什么方法可以让我在将它放到画布上时提高疯狂大图像加载的速度?

有没有办法可以使用某种流方法将图像加载到块中? 有没有办法阻止应用程序在加载图像时锁定?

可以在此处找到用于测试的图像:http://www.finwe.mobi/orion360/test/equi/Orion360_test_image_8192x4096.jpg

最终结果图像将大于此。

Main.cs

using System;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Imaging;

namespace WpfApplication1
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

            ImageBrush ib = new ImageBrush();
            ib.ImageSource = new BitmapImage(new Uri(@"C:\Users\jmartini\Projects\wpf_image_streamer\testImage.png", UriKind.Relative));
            //mycanvas.Background = ib;
            canvas_view.Background = ib;
        }
    }
}

Main.XMAL

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApplication1"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <Canvas Name="canvas_view"></Canvas>
    </Grid>
</Window>

1 个答案:

答案 0 :(得分:1)

您需要在后台线程上加载图像,以防止应用程序无响应。您可以考虑首先显示图像的低分辨率版本,以便在应用程序加载大版本时用户可以查看。您还需要考虑显示进度条,以及在图像仍在加载时用户应该能够与之交互的UI元素。

虽然当您开始将异步代码与用户界面混合时需要考虑很多事情,但最基本的用例仍然相对简单。以下示例应该让您入门:

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();

        var brush = new ImageBrush(new BitmapImage(new Uri("thumbnail.jpg", UriKind.Relative)));
        canvas_view.Background = brush;
        this.Loaded += MainWindow_Loaded;
    }

    async void MainWindow_Loaded(object sender, RoutedEventArgs e)
    {
        var bi = await LoadBigImage();
        canvas.Background = new ImageBrush(bi);
    }

    async Task<BitmapImage> LoadBigImage()
    {
        var bi = new BitmapImage(new Uri("fullsize.jpg", UriKind.Relative));
        bi.Freeze(); // note: must freeze DP objects when passing between threads
        return bi;
    }
}
相关问题