2010-03-23 223 views
0

我正在加載圖層圖層來製作單個圖像。我目前將它們全部堆疊到畫布上。我已經設置好了,所以用戶可以指定單個圖像的最終尺寸,但即使改變畫布尺寸,圖像也會保留其原始尺寸。WPF圖像裁剪

我試圖修改圖像的大小,因爲我正在加載它們,但尺寸是NaN,實際尺寸是0,所以我無法在那裏更改它們。

我開始認爲畫布可能不是要走的路。有關我如何剪裁圖像以適合特定尺寸的任何建議?

 canvas1.Children.Clear(); 
     int totalImages = Window1.GetNumberOfImages(); 
     if (drawBackground) 
      canvas1.Background = new SolidColorBrush(Color.FromArgb(a,r,g,b)); 
     else 
      canvas1.Background = new SolidColorBrush(Color.FromArgb(0, 0, 0, 0)); 

     for (int i = 0; i < totalImages; i++) 
     { 
      Image image = new Image(); 
      image.Source = Window1.GetNextImage(i); 

      canvas1.Children.Add(image);     
     } 

回答

1

要獲得當前的畫布尺寸,您必須先致電MeasureArrange。這將避免NaN和0。

使用RenderTransform更改Canvas顯示的圖像的大小。

我從來沒有嘗試裁剪圖像,所以我不知道該怎麼做,但我看到有一個CroppedBitmap對象。我猜你已經試過了?

+0

還沒有嘗試過,甚至都不知道!一旦我可以回到自己的電腦,我會試一試。 – Califer 2010-03-23 22:16:54

+0

我將for循環的內部更改爲以下內容,現在可以使用。 Image image = new Image(); BitmapSource tempSource = Window1.GetNextImage(i); CroppedBitmap CB =新CroppedBitmap(tempSource, 新Int32Rect(0,0, Math.Min((int)的Window1.totalWinWidth,tempSource.PixelWidth) Math.Min((int)的Window1.totalWinHeight, tempSource.PixelHeight))); image.Source = cb; canvas1.Children.Add(image); – Califer 2010-03-24 14:39:41

+0

> _ <我想我不能把代碼格式置於評論中...... – Califer 2010-03-24 14:41:05

0

對我來說似乎應該是修改圖像源的大小,而不僅僅是畫布。畫布只是一個容器,它不具有修改其子項的功能。

+0

對,這就是我想要做的。但是,當我加載它們的大小設置爲NaN和0. – Califer 2010-03-23 21:29:09

+0

從Window1.GetNextImage(i)返回的對象的類型是什麼?那是NaN和0? – 2010-03-23 21:57:20

+0

這是一個BitmapSource。我確信它有適合尺寸的正確信息,但是當我將它加載到圖像中時,圖像沒有正確的尺寸。 – Califer 2010-03-23 22:06:26

3

對於其他正在做同樣的事情的人來說,這裏是我工作的代碼。謝謝Jeffrey!

  Image image = new Image(); 
      BitmapSource tempSource = Window1.GetNextImage(i); 
      CroppedBitmap cb = new CroppedBitmap(tempSource, 
         new Int32Rect(0, 0, 
          Math.Min((int)Window1.totalWinWidth, tempSource.PixelWidth), 
          Math.Min((int)Window1.totalWinHeight, tempSource.PixelHeight))); 
      image.Source = cb; 

      canvas1.Children.Add(image); 
+0

不客氣!很高興我能幫上忙。 :-) – 2010-03-24 14:46:48