2011-07-19 54 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,可以獲得更好的結果。儘管如此,它仍然會產生僞像,但它的外觀會產生一些內部舍入誤差。不知道,我不得不猜測「事實」的價值。

避免縮放小的位圖。