Drawing Pixels in WPF

后端 未结 5 904
日久生厌
日久生厌 2020-12-01 06:37

how would I manage pixel-by-pixel rendering in WPF (like, say, for a raytracer)? My initial guess was to create a BitmapImage, modify the buffer, and display that in an Imag

5条回答
  •  误落风尘
    2020-12-01 06:59

    If you are thinking of doing something like a ray tracer where you will need to be plotting lots of points you will probably want to draw in the bitmap's memory space directly instead of through the layers of abstraction. This code will give you significantly better render times, but it comes at the cost of needing "unsafe" code, which may or may not be an option for you.

    
                unsafe
                {
                    System.Drawing.Point point = new System.Drawing.Point(320, 240);
                    IntPtr hBmp;
                    Bitmap bmp = new Bitmap(640, 480);
                    Rectangle lockRegion = new Rectangle(0, 0, 640, 480);
                    BitmapData data = bmp.LockBits(lockRegion, ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);
                    byte* p;
    
                    p = (byte*)data.Scan0 + (point.Y * data.Stride) + (point.X * 3);
                    p[0] = 0; //B pixel
                    p[1] = 255; //G pixel
                    p[2] = 255; //R pixel
    
                    bmp.UnlockBits(data);
    
                    //Convert the bitmap to BitmapSource for use with WPF controls
                    hBmp = bmp.GetHbitmap();
                    Canvas.Source = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(hbmpCanvas, IntPtr.Zero, Int32Rect.Empty, System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions());
                    Canvas.Source.Freeze();
                    DeleteObject(hBmp); //Clean up original bitmap
                }
    

    To clean up the hBitmap you will need to declare this near the top of your class file:

    
            [System.Runtime.InteropServices.DllImport("gdi32.dll")]
            public static extern bool DeleteObject(IntPtr hObject);
    

    Also note that you will need to set the project properties to allow unsafe code. You can do this by right clicking on the project in solution explorer and selecting properties. Goto the Build tab. Check the "Allow unsafe code" box. Also I believe you will need to add a reference to System.Drawing.

提交回复
热议问题