简体   繁体   English

从二进制数据重复设置image.source

[英]Repeatedly set image.source from binary data

I use the following to set an image to the byte data. 我使用以下内容将图像设置为字节数据。 However, after the first call, the image no longer changes in response to the data. 但是,在第一次调用后,图像不再响应数据而改变。

public async void SetImageFromByteArray(byte[] data)
    {
        using (InMemoryRandomAccessStream raStream =
            new InMemoryRandomAccessStream())
        {
            using (DataWriter writer = new DataWriter(raStream))
            {
                // Write the bytes to the stream
                writer.WriteBytes(data);

                // Store the bytes to the MemoryStream
                await writer.StoreAsync();

                // Not necessary, but do it anyway
                await writer.FlushAsync();

                // Detach from the Memory stream so we don't close it
                writer.DetachStream();
            }

            raStream.Seek(0);

            BitmapImage bitMapImage = new BitmapImage();
            bitMapImage.SetSource(raStream);
            GameScreen.Source = bitMapImage;
            await raStream.FlushAsync();
        }
    }

Also, I would kind of like to be able to run this function every "x" milliseconds, but I haven't been able to find a way to do it. 另外,我希望能够每隔“ x”毫秒运行一次此功能,但我一直找不到能够做到这一点的方法。

Its impossible to tell for sure without seeing the rest of your code, but if this function is called repeatedly, then you are probably not making the subsequent calls from the UI thread which would cause an exception when creating/accessing the BitmapImage and UI Image source. 在看不到代码其余部分的情况下无法确定,但是如果重复调用此函数,则可能无法从UI线程进行后续调用,这会在创建/访问BitmapImage和UI Image源时引起异常。 These calls must be called from the UI thread. 必须从UI线程调用这些调用。 Wrap the last few lines of code in a Dispatch call like this: 将Dispatch调用中的最后几行代码包装如下:

        await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, async () =>
        {
           BitmapImage bitMapImage = new BitmapImage();
           bitMapImage.SetSource(raStream);
           GameScreen.Source = bitMapImage;
           await raStream.FlushAsync();
        });

This will make sure that these calls are run on the UI thread. 这将确保这些调用在UI线程上运行。

For the timer part of your question, there are several options. 对于您的问题的计时器部分,有几种选择。 I am not a big fan of using timers so I would probably create a thread with a simple loop that sleeps between calls: 我不是使用计时器的忠实拥护者,因此我可能会创建一个带有在调用之间休眠的简单循环的线程:

            Task.Run((async () =>
            {
                while(!stop)
                {
                   byte [] data = GetNextImageBytes();
                   await SetImageFromByteArray(data);
                   await Task.Delay(2000);
                }
            });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM