2

当我尝试使用以下方法将此位图绘制为 2 像素宽时,我创建了一个 1 像素宽和 256 像素高的位图:

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);
    }           
}
4

3 回答 3

2

这是 Graphics.InterpolationMode 的副作用,当位图边缘的像素用完时,位图缩放会产生伪影。并且有很多像素用完的位图只有一个像素宽。您可以通过将其设置为 NearestNeighbor 并将 PixelOffsetMode 设置为 None 来获得更好的结果。尽管如此,这仍然会产生伪影,从外观上看会产生一些内部舍入误差。不确定,我不得不猜测“事实”的价值。

避免缩放小位图。

于 2011-07-19T09:28:41.220 回答
1
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(位图,矩形);您正在矩形上绘制 1 像素宽的位图,从 x 坐标等于 0 开始。

  • 循环结束,x 变为 1。

  • 左上 x 坐标现在是 2。

  • 在矩形上绘制 1 像素宽的位图,从等于 2 的 x 坐标开始。 (如您所见,没有位图 @ 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()方法吗?

于 2011-07-19T08:58:46.317 回答
0

bitmap.SetPixel(1,y,Color.Red) 应该这样做,而 rectf.X 不应该扩展 rectf.Width。

于 2011-07-19T08:15:21.590 回答