2010-09-25 102 views
0

下載的圖像,我需要下載一個網絡攝像頭圖像直通HTTP,在10fps的刷新並顯示一個WPF窗口。現在,我使用此代碼:如何顯示在WPF窗口

Window1 wndMain; 
    BitmapImage img; 
    DispatcherTimer tmrRefresh; 
    public WCam(Window1 wndMain, string imguri) 
    { 
     this.wndMain = wndMain; 
     this.MouseLeftButtonDown += delegate { DragMove(); }; 
     url = imguri; 
     InitializeComponent(); 
     tmrRefresh = new DispatcherTimer(TimeSpan.FromMilliseconds(100), 
     DispatcherPriority.Normal, Refresh, Dispatcher.CurrentDispatcher); 
    } 

    private void Window_Loaded(object sender, RoutedEventArgs e) 
    { 
     if (url != "") 
     { 
      try 
      { 
       img = new BitmapImage(); 
       img.BeginInit(); 
       img.CacheOption = BitmapCacheOption.OnLoad; 
       img.CreateOptions = BitmapCreateOptions.IgnoreImageCache; 
       img.UriSource=(new Uri(url)); 
       img.EndInit(); 
      } 
      catch (Exception ex) 
      { 
       new WPopup().Show(ex.Message); 
      } 
      ImgBox.Source = img; 
      tmrRefresh.Start(); 
     } 

    } 
    public void Refresh(object sender, EventArgs e) 
    { 
     try 
     { 
      img = new BitmapImage(); 
      img.BeginInit(); 
      img.CacheOption = BitmapCacheOption.OnLoad; 
      img.CreateOptions = BitmapCreateOptions.IgnoreImageCache; 
      img.UriSource = (new Uri(url)); 
      img.EndInit(); 
     } 
     catch (Exception ex) 
     { 
      new WPopup().Show(ex.Message); 
     } 
     ImgBox.Source = null; 
     ImgBox.Source = img; 
    } 

它顯示什麼,如果我增加計時器的時間間隔爲1000它顯示的圖像,但圖像消失,同時它加載下一個。此外窗口非常緩慢地加載。

回答

0

分離圖像中的加載邏輯。 保持加載的代碼原樣,刷新應該用簡單的異步(保持ui運行)請求下載圖像,並且只有在完成後纔將圖像源更改爲本地內存。