2011-07-19 53 views
2

我已经创建的位图1个像素宽& 256像素高度当我尝试绘制这个位图作为2个像素宽使用:的DrawImage()功能不起作用正确

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); 
    }   
} 
+0

为什么位图的高度做得不如目标矩形高? – Tigran

回答

0

bitmap.SetPixel(1,Y,Color.Red)可以这样做,并rectf.X不应延伸rectf.Width的简单代码。

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(bitmap,rectf);您是矩形绘制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()方法?

2

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

避免缩放小的位图。