WriteableBitmap在ui上的线程节目上生成

时间:2016-01-20 06:46:30

标签: c# wpf writeablebitmap writeablebitmapex

从我读过和发现的关于writablebitmap的内容来看,我无法在不同的线程中更改它,而是创建它的那个。但我应该能够在不同的线程上创建它,然后是UI线程,然后将其解冻并解析为UI线程以供显示。示例:Thread cannot access the object

但是,当我这样做时,请告诉我"调用线程无法访问此对象,因为另一个线程拥有它。"当我冻结位图时,这是谁?

 public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            Timer imageTimer = new Timer(41);
            imageTimer.Elapsed += async (sender, args) =>
            {
                ImageSource image = await GetImage((int)Math.Ceiling(Image.Width), (int)Math.Ceiling(Image.Height));
                DispatcherHelper.CheckBeginInvokeOnUI(() => {
                    Image.Source = image;
                });
            };
            imageTimer.Start();
        }

        public Task<WriteableBitmap> GetImage(int width, int height)
        {
            return Task.Factory.StartNew(() =>
            {
                WriteableBitmap bitmap = BitmapFactory.New(width, height);
                using (bitmap.GetBitmapContext())
                {
                    bitmap.Clear(System.Windows.Media.Colors.AliceBlue);

                    Random rnd = new Random();
                    Color[] Colors = new Color[100];
                    for (int i = 0; i <= 99; i++)
                    {
                        Colors[i] = Color.FromRgb((byte)rnd.Next(0, 255), (byte)rnd.Next(0, 255),
                            (byte)rnd.Next(0, 255));
                    }

                    double size = width / 50;
                    for (int i = 0; i <= 49; i++)
                    {
                        int from = (int)Math.Ceiling(size * (double)i);
                        int to = (int)Math.Ceiling(size * (double)(i + 1)) - 1;
                        var color = Colors[i];

                        bitmap.DrawFilledRectangle(from, 0, to, height, color);
                    }
                }

                bitmap.Freeze();
                return bitmap;
            });
        }
    }

    public static class KasperWriteableBitMapExtentions
    {
        public static void DrawFilledRectangle(this WriteableBitmap bmp, int x1, int y1, int x2, int y2, Color color)
        {
            // Use refs for faster access (really important!) speeds up a lot!
            int w = bmp.PixelWidth;
            int h = bmp.PixelHeight;

            // Check boundaries
            if (x1 < 0) { x1 = 0; }
            if (y1 < 0) { y1 = 0; }
            if (x2 < 0) { x2 = 0; }
            if (y2 < 0) { y2 = 0; }
            if (x1 > w) { x1 = w; }
            if (y1 > h) { y1 = h; }
            if (x2 > w) { x2 = w; }
            if (y2 > h) { y2 = h; }

            for (int y = y1; y < y2; y++)
            {
                for (int x = x1; x <= x2; x++)
                {
                    bmp.SetPixel(x, y, color);
                }
            }
        }
    }

0 个答案:

没有答案