2012-10-21 225 views
0

我想從嵌入式資源加載圖像到Image實例。問題是圖像的大小始終爲0圖像大小總是返回0

這裏是代碼片段:

Image image = new Image(); 
ImageSource img = new System.Windows.Media.Imaging.BitmapImage(new Uri("/Images/marker.png", UriKind.Relative)); 
image.SetValue(Image.SourceProperty, img); 


System.Diagnostics.Debug.WriteLine("output 1 = " + image.DesiredSize.Width); // return 0 
System.Diagnostics.Debug.WriteLine("output 2 = " + image.ActualWidth); // return 0 

我要知道之前呈現在屏幕上的圖像的大小,因爲我需要偏移圖像取決於它的大小。

謝謝



更新: 感謝Silvermind

我回答我自己的問題與示例代碼

+0

它沒有'DesiredSize'它是在UI渲染之前。 – Silvermind

+0

在UI上呈現之前是否可以獲取圖像大小? –

+0

在渲染前獲取控件大小並不是真正可行的:http://msdn.microsoft.com/en-us/library/system.windows.frameworkelement.actualwidth(v=vs.95).aspx在Silverlight中,它更好想想使用Horizo​​ntalAligment等進行自動定位,或許最好告訴我們你想要完成什麼。 – Silvermind

回答

0

謝謝Silvermind。他建議使用CreateOptions。

最後,我找到了一個解決方案:

Image image = new Image(); 

Uri uri = new Uri("/Images/marker_stop.png", UriKind.Relative); 
BitmapImage bi = new BitmapImage(uri); 
bi.CreateOptions = BitmapCreateOptions.IgnoreImageCache; 

image.Source = bi; 
System.Diagnostics.Debug.WriteLine("************************************* in image.ActualWidth " + ", " + bi.PixelWidth); // return 30 
1

「/Images/marker.png」 - 是你相信這裏是文件?

也許是因爲該文件夾被命名爲圖像沒有大寫我?

還什麼返回:

image.getValue(); // here what null? after setting it 
+0

我確定圖像路徑是正確的,因爲它可以在屏幕上呈現。 –

2

縱觀BitmapImage.DownloadProgress Event;

通過URI構造BitmapImage是固有異步的。這個事件報告了建設進度。

換句話說,在BitmapImage運行前ActualWidth也必然被下載/構造很可能返回0作爲ActualWidth