DrawImage()函数在WinForms上不能正常工作

本文关键字:常工作 工作 不能 WinForms 函数 DrawImage | 更新日期: 2023-09-27 18:02:24

我已经创建了一个1像素宽的位图&当我尝试将此位图绘制为2像素宽时,使用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);
    }           
}

DrawImage()函数在WinForms上不能正常工作

这是图形的副作用。InterpolationMode,位图缩放在位图边缘的像素耗尽时会产生伪影。对于一个只有一个像素宽的位图,会有很多像素耗尽。你可以通过将其设置为NearestNeighbor和将PixelOffsetMode设置为None来获得更好的结果。尽管如此,这仍然会产生一些工件,一些内部舍入错误。不确定,我只能猜"fact"的值

避免缩放小位图

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。rectf DrawImage(位图);您正在矩形上绘制1像素宽的位图,从x坐标等于0开始

  • 循环结束,x变为1

  • 左上角x轴现在是2

  • 在矩形上绘制1像素宽的位图,从x坐标等于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);    
}

注:你想达到什么目标?你听说过graphics。fillrectangle()方法吗?

bitmap.SetPixel(1,y,Color.Red)应该这样做并进行校正。X不应该扩展rect . width .