1

我正在将图像加载到我的 silverlight 应用程序中。该图像将适合作为纹理贴图的 3d 模型。我需要获取图像属性。为此,我正在使用 ImageOpened 事件,如下所示:

public MainPage()
    {

        BitmapImage img = new BitmapImage(new Uri("imagens/textura.jpg", UriKind.Relative));

        img.ImageOpened += new EventHandler<RoutedEventArgs>(img_ImageOpened);
        img.ImageFailed += new EventHandler<ExceptionRoutedEventArgs>(img_ImageFailed);
        imageBrush.ImageSource = img;

        InitializeComponent();

        this.Loaded += new RoutedEventHandler(MainPage_Loaded);

        this.MouseLeftButtonUp += new MouseButtonEventHandler(MainPage_MouseLeftButtonUp); 

(...)

进而:

private void img_ImageOpened(object sender, RoutedEventArgs e)
    {
        BitmapImage i = sender as BitmapImage;
        ImgSize.Width  = i.PixelWidth;
        ImgSize.Height = i.PixelHeight;
        MessageBox.Show("LOADED IMAGE SIZE\n W:" + ImgSize.Width.ToString() + "  H:" + ImgSize.Height.ToString());

    }

消息框显示加载图片的正确值。但是这是在加载场景后运行的,所以大小总是默认的(0,0)......我不知道如何解决这个问题。我已经运行了调试器,我注意到场景和模型被渲染并且图片的宽度和高度为零。在此之后,事件被触发......我无法弄清楚。

提前致谢,

何塞

4

1 回答 1

1

首先,这有点令人困惑:-

    imageBrush.ImageSource = img;

    InitializeComponent();

除非你有一些非常不寻常的事情发生,否则imageBrush对象将在InitializeComponent运行之后为空。

至于您猜测的问题,您将 3D 模型加载到MainPage_Loaded. 那么问题是他的发生与位图的到达是异步的。Loaded因此,在和ImageOpened事件都发生之前,您不希望实际加载 3D 模型。请注意,假设这ImageOpened总是最后发生是很危险的。

我能想到的最简单的解决方案是在MainPage_Loaded事件中移动所有现有代码,ImageOpened然后将获取图像的代码移动到MainPage_Loaded. ImageOpened当您的执行保证页面已加载时,这将序列化序列。

Not the most sophisticated solution and doesn't make use of benefits of the asynchronous nature of SL. However it should get you going and you can assess whether there is any benefit in having Page loading and bitmap downloading operating in parallel.

于 2009-11-20T11:45:06.403 回答