代码之家  ›  专栏  ›  技术社区  ›  Mark T

在Windows窗体上绘制单个像素

  •  84
  • Mark T  · 技术社区  · 16 年前

    我一直在尝试打开Windows窗体上的单个像素。

    graphics.DrawLine(Pens.Black, 50, 50, 51, 50); // draws two pixels
    
    graphics.DrawLine(Pens.Black, 50, 50, 50, 50); // draws no pixels
    

    API确实应该有一个方法来设置一个像素的颜色,但我看不到。

    我用C语言。

    7 回复  |  直到 9 年前
        1
  •  106
  •   Henk Holterman    16 年前

    这将设置一个像素:

    e.Graphics.FillRectangle(aBrush, x, y, 1, 1);
    
        2
  •  17
  •   Adam Robinson    16 年前

    这个 Graphics 对象没有这个,因为它是抽象的,可以用来覆盖向量图形格式。在这种情况下,设置单个像素是没有意义的。这个 Bitmap 图像格式确实有 GetPixel() SetPixel() 但不是建立在一个图形对象上的图形对象。对于您的场景,您的选项似乎是唯一的一个,因为没有一个大小适合所有的方式来设置一个普通图形对象的单个像素(并且您不知道它是什么,因为您的控件/窗体可能是双缓冲的,等等)。

    为什么需要设置一个像素?

        3
  •  17
  •   WoodyDRN    11 年前

    只需显示Henk Holterman答案的完整代码:

    Brush aBrush = (Brush)Brushes.Black;
    Graphics g = this.CreateGraphics();
    
    g.FillRectangle(aBrush, x, y, 1, 1);
    
        4
  •  9
  •   Will Dean    16 年前

    在我绘制大量单像素(用于各种定制数据显示)的地方,我倾向于将它们绘制成位图,然后将其快速放到屏幕上。

    位图getPixel和setPixel操作不是特别快,因为它们执行了大量的边界检查,但是很容易生成一个“快速位图”类,该类可以快速访问位图。

        5
  •  1
  •   Rytmis    16 年前

    显然,绘制的线条比实际指定长度短一个像素。似乎没有DrawPoint/DrawPixel/WhatNot,但是您可以使用宽度和高度设置为1的DrawRectangle绘制单个像素。

        6
  •  1
  •   nor    10 年前

    MSDN Page on GetHdc

    我想这就是你要找的。您需要获取HDC,然后使用gdi调用来使用setpixel。注意,gdi中的colorRef是存储bgr颜色的dword。没有alpha通道,也不像gdi+的颜色结构那样是RGB。

    这是我为完成相同任务而编写的一小段代码:

    public class GDI
    {
        [System.Runtime.InteropServices.DllImport("gdi32.dll")]
        internal static extern bool SetPixel(IntPtr hdc, int X, int Y, uint crColor);
    }
    
    {
        ...
        private void OnPanel_Paint(object sender, PaintEventArgs e)
        {
            int renderWidth = GetRenderWidth();
            int renderHeight = GetRenderHeight();
            IntPtr hdc = e.Graphics.GetHdc();
    
            for (int y = 0; y < renderHeight; y++)
            {
                for (int x = 0; x < renderWidth; x++)
                {
                    Color pixelColor = GetPixelColor(x, y);
    
                    // NOTE: GDI colors are BGR, not ARGB.
                    uint colorRef = (uint)((pixelColor.B << 16) | (pixelColor.G << 8) | (pixelColor.R));
                    GDI.SetPixel(hdc, x, y, colorRef);
                }
            }
    
            e.Graphics.ReleaseHdc(hdc);
        }
        ...
    }
    
        7
  •  -1
  •   Eddy    9 年前

    使用带dashStyle.dashStyle.dot的笔绘制直线2px可绘制单个像素。

        private void Form1_Paint(object sender, PaintEventArgs e)
        {
            using (Pen p = new Pen(Brushes.Black))
            {
                p.DashStyle = System.Drawing.Drawing2D.DashStyle.Dot;
                e.Graphics.DrawLine(p, 10, 10, 11, 10);
            }
        }