SetPixel is too slow. Is there a faster way to draw to bitmap?

前端 未结 5 450
生来不讨喜
生来不讨喜 2020-11-30 06:08

I have a small paint program that I am working on. I am using SetPixel on a bitmap to do that drawing of lines. When the brush size gets large, like 25 pixels across there i

5条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-30 06:51

    You can lock the bitmap data and use pointers to manually set the values. It's much faster. Though you'll have to use unsafe code.

    public override void PaintPoint(Layer layer, Point position)
        {
            // Rasterise the pencil tool
    
            // Assume it is square
    
            // Check the pixel to be set is witin the bounds of the layer
    
            // Set the tool size rect to the locate on of the point to be painted
            m_toolArea.Location = position;
    
            // Get the area to be painted
            Rectangle areaToPaint = new Rectangle();
            areaToPaint = Rectangle.Intersect(layer.GetRectangle(), m_toolArea);
    
            Bitmap bmp;
            BitmapData data = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);
            int stride = data.Stride;
            unsafe
            {
                byte* ptr = (byte*)data.Scan0;
                // Check this is not a null area
                if (!areaToPaint.IsEmpty)
                {
                    // Go through the draw area and set the pixels as they should be
                    for (int y = areaToPaint.Top; y < areaToPaint.Bottom; y++)
                    {
                        for (int x = areaToPaint.Left; x < areaToPaint.Right; x++)
                        {
                            // layer.GetBitmap().SetPixel(x, y, m_colour);
                            ptr[(x * 3) + y * stride] = m_colour.B;
                            ptr[(x * 3) + y * stride + 1] = m_colour.G;
                            ptr[(x * 3) + y * stride + 2] = m_colour.R;
                        }
                    }
                }
            }
            bmp.UnlockBits(data);
        }
    

提交回复
热议问题