我卡在了尝试在Windows Form上打开单个像素的问题上。
graphics.DrawLine(Pens.Black, 50, 50, 51, 50); // draws two pixels
graphics.DrawLine(Pens.Black, 50, 50, 50, 50); // draws no pixels
API确实应该有一个方法来设置一个像素的颜色,但我没有找到这样的方法。
我正在使用C#。
我卡在了尝试在Windows Form上打开单个像素的问题上。
graphics.DrawLine(Pens.Black, 50, 50, 51, 50); // draws two pixels
graphics.DrawLine(Pens.Black, 50, 50, 50, 50); // draws no pixels
API确实应该有一个方法来设置一个像素的颜色,但我没有找到这样的方法。
我正在使用C#。
这将设置单个像素:
e.Graphics.FillRectangle(aBrush, x, y, 1, 1);
DrawRectangle()
的笔对象。 如果它具有Pen.Alignment = PenAlignment.Outset
,它将会在所给出的矩形周围绘制 Pen.Width
像素粗的轮廓线。但是,如果您指定了 Pen.Alignment = PenAlignment.Inset
,它将在给定的矩形内部绘制与 Pen.Width
相同像素粗度的“轮廓线”。 - Cipie.Graphics.FillRectangle(aBrush, x - 0.5f, y - 0.5f, 1.0f, 1.0f);
- AdamGraphics
对象并没有这个功能,因为它是一个抽象的对象,可以用来覆盖矢量图形格式。在这种情况下,设置单个像素是没有意义的。Bitmap
图像格式确实有GetPixel()
和SetPixel()
方法,但没有建立在此之上的图形对象。对于您的情况,您的选择似乎真的是唯一的,因为没有通用的方法来设置通用图形对象的单个像素(而且您不知道它到底是什么,因为您的控件/表单可能已经双缓冲等)。
你为什么需要设置单个像素?
为了展示Henk Holterman回答的完整代码:
Brush aBrush = (Brush)Brushes.Black;
Graphics g = this.CreateGraphics();
g.FillRectangle(aBrush, x, y, 1, 1);
当我绘制许多单像素点(用于各种自定义数据显示)时,我倾向于将它们绘制到一个位图中,然后将其贴在屏幕上。
由于Bitmap GetPixel和SetPixel操作进行了大量的边界检查,因此它们不是特别快。但相对容易创建一个“快速位图”类,该类可以快速访问位图。
我认为这是您正在寻找的内容。您需要获取 HDC,然后使用 GDI 调用来使用 SetPixel。请注意,GDI 中的 COLORREF 是存储 BGR 颜色的 DWORD。它没有 Alpha 通道,并且不像 GDI+ 的 Color 结构体那样是 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);
}
...
}
Pixel[,]
的IntPtr将位图的左上坐标指向某个任意的[y,x]
坐标。 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);
}
}
如果您正在使用SmoothingMode = AntiAlias绘制图形,大多数绘图方法将绘制多个像素。如果您只想绘制一个像素,请创建一个1x1位图,将位图的像素设置为所需的颜色,然后在图形上绘制该位图。
using (var pixel = new Bitmap(1, 1, e.Graphics))
{
pixel.SetPixel(0, 0, color);
e.Graphics.DrawImage(pixel, x, y);
}
显然,DrawLine 画的线比实际指定的长度短一个像素。似乎没有 DrawPoint/DrawPixel/等等这样的函数,但是你可以使用将宽度和高度设置为1的 DrawRectangle 函数来绘制单个像素。
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void Form1_Paint(object sender, PaintEventArgs e)
{
Brush aBrush = (Brush)Brushes.Red;
Graphics g = this.CreateGraphics();
g.FillRectangle(aBrush, 10, 10, 1, 1);
}
}