WinForms上的DrawImage()函数无法正常工作
当我尝试使用以下方法将此位图绘制为2像素宽时,我创建了一个1像素宽和256像素高的BitMap:
public void DrawImage(Image image,RectangleF rect)
由于每个位图列之间有白色细条纹,因此未正确绘制位图。 请参阅下面的简单代码
private void Form1_Paint(object sender, PaintEventArgs e) { Graphics gr = e.Graphics; Bitmap bitmap = new Bitmap(1, 256); for (int y = 0; y < 256; y++) { bitmap.SetPixel(0, y, Color.Red); } RectangleF rectf = new RectangleF(); for (int x = 0; x < 500; x++) { float factor = 2; rectf.X = x*factor; rectf.Y = 0; rectf.Width = fact; rectf.Height = 500; // should draw bitmap as 2 pixels wide but draws it with white slim stripes in between each bitmap colomn gr.DrawImage(bitmap, rectf); } }
这是Graphics.InterpolationMode的副作用,位图缩放在位图边缘的像素用完时会产生伪像。 并且有很多像素耗尽的位图只有一个像素宽。 通过将其设置为NearestNeighbor并将PixelOffsetMode设置为None,可以获得更好的结果。 这仍然会产生伪影,但它的外观会产生一些内部的舍入误差。 不确定,我不得不猜测“事实”的价值。
避免缩放小位图。
for (int x = 0; x < 500; x++) { float factor = 2; rectf.X = x*factor; rectf.Y = 0; rectf.Width = fact; rectf.Height = 500; // should draw bitmap as 2 pixels wide // but draws it with white slim stripes in between // each bitmap colomn gr.DrawImage(bitmap, rectf); }
这是你的片段。 并且你坚持认为should draw bitmap as 2 pixels wide
。 对不起,但这是错的。 我会解释原因。 让我们来看看这个循环是如何工作的。
-
x=0
-
您将左上角x坐标设置为零。
rectf.X = x*factor;
-
gr.DrawImage(bitmap,rectf); 你在矩形上绘制1像素宽的位图,从x coord开始等于0。
-
循环结束,x变为1。
-
左上角x coord现在是2。
-
在矩形上绘制1个像素宽的位图,从x coord开始等于2. (如您所见,没有位图@ x = 1)
我是否必须继续,或者是否清楚为什么白色条纹来自哪里?
修复它使用此代码段
for (int x = 0; x < 500; x++) { float factor = 2; rectf.X = x * factor; // x coord loops only through even numbers, thus there are white stripes rectf.Y = 0; rectf.Width = factor; rectf.Height = 500; // should draw bitmap as 2 pixels wide // but draws it with white slim stripes in between // each bitmap colomn gr.DrawImage(bitmap, rectf); rectf.X = x * factor + 1; // now x coord also loops through odd numbers, and combined with even coords there will be no white stripes. gr.DrawImage(bitmap, rectf); }
PS你想要实现什么目标? 你听说过Graphics.FillRectangle()方法吗?
bitmap.SetPixel(1,y,Color.Red)应该这样做,而rectf.X不应该扩展rectf.Width。