WPF图像:在多个源更新后获取实际大小

BFi*_*Fil 5 size wpf image wpf-controls

我正在根据ComboBox选择更新图像控件的Source.

更新图像源后,我需要读取图像的ActualWidth和ActualHeight

我在第一次使用Image控件的Loaded事件打开对话框时工作,但是每次更新Source时这个事件都没有明显提升.

有没有办法在每次Source更新后获得加载到控件中的图像的实际大小?

osM*_*ike 0

您可以尝试使用图像源更新事件,但我并不总是有运气使用此事件。

根据您的源,更好的解决方案是在加载时添加一个处理程序。

你可以尝试这样的事情:

Dim src As BitmapImage = New BitmapImage()
src.BeginInit()
src.UriSource = tURI
src.CacheOption = BitmapCacheOption.OnLoad
src.EndInit()
imgImage.SetCurrentValue(Image.SourceProperty, src)
AddHandler src.DownloadCompleted, AddressOf ImageDownloadCompleted
Run Code Online (Sandbox Code Playgroud)

然后你可以编写ImageDownloadCompleted的代码来获取图像的实际高度和宽度。

为了获得实际宽度,我使用源图像的宽度而不是图像控件,如下所示:

Sub ImageDownloadCompleted(sender As Object, e As System.EventArgs)
    Dim src As BitmapImage
    Dim dwidth as Double
    Dim dheight as Double

    src = DirectCast(sender, BitmapImage)
    dwidth = src.Width 
    dheight = src.Height
    RemoveHandler src.DownloadCompleted, AddressOf ImageDownloadCompleted
End Sub
Run Code Online (Sandbox Code Playgroud)