简体   繁体   中英

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.

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. These calls must be called from the UI thread. Wrap the last few lines of code in a Dispatch call like this:

        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.

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);
                }
            });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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