LoginSignup
1
1

More than 3 years have passed since last update.

[C#/UWP] WriteableBitmapで点を打って、テレビの放送終了後の砂嵐をつくる(UWP版)

Posted at

もくじ
https://qiita.com/tera1707/items/4fda73d86eded283ec4f

やりたいこと

以前、WPFで同じことを試したが、そのままのコードをWPFにもっていっても動かなった。
WriteableBitmapクラスはUWPにもあるが、仕様が異なっているからと思われる。
また、別スレッド中に、UIスレッドで処理をしてもらうための書き方(Dispatcher.Invoke())も、WPFとUWPで異なっている。

UWPでも画面に点を打つことがあるので、やり方を知りたい。

サンプル

下記のようにすると動いた。

MainPage.xaml.cs
using System;
using System.Threading.Tasks;
using Windows.Graphics.Imaging;
using Windows.Storage.Streams;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Media.Imaging;

namespace SandStormUWP
{
    public sealed partial class MainPage : Page
    {
        public MainPage()
        {
            this.InitializeComponent();

            Task.Run(() =>
            {
                while (true)
                {
                    const int width = 256;
                    const int height = 256;

                    byte[] data = new byte[width * height * 4];

                    Random rnd = new System.Random();    // インスタンスを生成
                    int rndMax = 256;                    // 0~256の乱数を取得

                    // バイト列に色情報を入れる
                    for (int i = 0; i < width; i++)
                    {
                        for (int j = 0; j < height; j++)
                        {
                            data[4 * (i + j * width)] = (byte)rnd.Next(rndMax);
                            data[4 * (i + j * width) + 1] = (byte)rnd.Next(rndMax);
                            data[4 * (i + j * width) + 2] = (byte)rnd.Next(rndMax);
                            data[4 * (i + j * width) + 3] = (byte)rnd.Next(rndMax);
                        }
                    }

                    var task = this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, async () =>
                    {
                        WriteableBitmap bitmap = new WriteableBitmap(width, height);

                        InMemoryRandomAccessStream inMRAS = new InMemoryRandomAccessStream();
                        BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, inMRAS);
                        encoder.SetPixelData(BitmapPixelFormat.Rgba8, BitmapAlphaMode.Ignore, (uint)bitmap.PixelWidth, (uint)bitmap.PixelHeight, 96.0, 96.0, data);
                        await encoder.FlushAsync();
                        BitmapImage bitmapImage = new BitmapImage();
                        bitmapImage.SetSource(inMRAS);
                        MyImage.Source = bitmapImage;   // 「MyImage」は、xamlの<Image Name="MyImage"/>より。砂嵐を張り付けるImageの名前。
                    });
                }
            });
        }
    }
}

image.png

参考

UWPでバイト配列を画像として表示する
https://jprogramer.com/uwp/3926

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1