简体   繁体   中英

How to draw in WPF by pixel

Necessary to draw by pixels array with data (large). How can I do that?

I tried a Canvas and Rectangle on it - the computer hanged himself ... Tried the following options below (DrawingContext) - computer still hangs himself, but a little bit less.

Please recommend options with the least load on the computer. int width = 800; - the size of the array (large!!!) int size = 1; - it is desirable to be able to make the fragment is not only one but several pixels

protected override void OnRender(System.Windows.Media.DrawingContext drawingContext)
        {
            Random rnd = new Random();
            int width = 800;
            int size = 1;
            CellType[,] types = new CellType[width, width];
            for (int i = 0; i < width; i++)
            {
                for (int j = 0; j < width; j++)
                {
                    int r = rnd.Next(0, 100);
                    if (r >= 70) types[j,i] = CellType.IsOccupied;
                    else types[j, i] = CellType.IsEmpty;
                }
            }


            for (int i = 0; i < width; i++)
            {
                for (int j = 0; j < width; j++)
                {
                    Brush brush = Brushes.Black;

                    switch (types[j, i])
                    {
                        case CellType.IsEmpty: brush = Brushes.Green;
                            break;
                        case CellType.IsOccupied: brush = Brushes.Black;
                            break;
                    }

                    drawingContext.DrawRectangle(brush,
                    new Pen(brush, 1),
                    new Rect(j * size, i * size, size, size));
                }
            }

            base.OnRender(drawingContext);
        }

For how long does it freeze? A couple of years ago I did something quite similar in Silverlight. It was a bit slow but still acceptable. Try using WriteableBitmap with SetPixel or FillRectangle methods, but please keep in mind that drawing pixel by pixel in a loop will always take some time.

Forgot to mention SetPixel and FillRectangle may need WriteableBitmapEx, available here: http://writeablebitmapex.codeplex.com/

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