2016-01-19 57 views
2

我試圖通過將一個疊加在另一個之上來創建圖像。代碼的作品,但我覆蓋的圖像似乎稍微拉伸,我無法解決原因。當疊加兩個相同大小的圖像時,一個是偏移量

因此,代碼只是創建一個空白的紅色24x24的矩形,然後我覆蓋一個24x24的PNG文件,該文件是這樣的:

enter image description here

我所期待的是:

enter image description here

但我實際得到這個:

enter image description here

Using backGround As New Bitmap(24, 24, Imaging.PixelFormat.Format32bppArgb) 
     Using g = Graphics.FromImage(backGround) 
      Using brush1 As New SolidBrush(Color.Red) 
       g.FillRectangle(brush1, 0, 0, 24, 24) 
       Using topimage = Image.FromFile("C:\Scratch\ManNoRecords24.png") 
        g.DrawImage(topimage, New Point(0, 0)) 
       End Using 
      End Using 
     End Using 
     backGround.Save("C:\Scratch\Emp.png", Imaging.ImageFormat.Png) 
    End Using 

調試表示topImage的屬性:

enter image description here

+0

在調試器中,檢查「t opimage'。他們是什麼? 24x24像你期望的那樣嗎? –

+0

是的,我檢查確實是24x24 –

+3

有可能是PNG文件中有一個不尋常的DPI?同樣的事情發生在不同的頂部圖像上嗎? – Eric

回答

4

可以使用

g.DrawImageUnscaledAndClipped(topimage, New Rectangle(0, 0, 24, 24)) 

代替,避免了源圖像的任何縮放同時提請它。這有效,但我實際上不太清楚你的解決方案有什麼問題。

Reference SourceDrawImageUnscaledAndClipped似乎用Pixel作爲圖像大小的默認單元,因此忽略源圖像的DPI設置:

/// <include file='doc\Graphics.uex' path='docs/doc[@for="Graphics.DrawImageUnscaledAndClipped"]/*' /> 
/// <devdoc> 
/// </devdoc> 
public void DrawImageUnscaledAndClipped(Image image, Rectangle rect) { 
    if(image == null) { 
     throw new ArgumentNullException("image"); 
    } 

    int width = Math.Min(rect.Width, image.Width); 
    int height = Math.Min(rect.Height, image.Height); 

    //We could put centering logic here too for the case when the image is smaller than the rect 
    DrawImage(image, rect, 0, 0, width, height, GraphicsUnit.Pixel); 
} 

DrawImageDrawImageUnscaled不,然後可能重新調整圖像基於其內部DPI設置,馬特發現它小於默認的96,這導致圖像的拉伸:

/// <include file='doc\Graphics.uex' path='docs/doc[@for="Graphics.DrawImageUnscaled"]/*' /> 
/// <devdoc> 
/// </devdoc> 
public void DrawImageUnscaled(Image image, Point point) { 
    DrawImage(image, point.X, point.Y); 
} 
+0

是的,我很好奇我自己。 – Jens

+1

看來backGround的水平分辨率和垂直分辨率都是96,而出於某種原因,磁盤上的PNG有71.9582,所以這會造成這個差異 –

+2

@MattWilko好的,這很難找到。我正在查看繪製圖像的參考源。當使用'DrawImageUnscaledAndClipped'時,.NET源代碼中的調用專門將'GraphicsUnit'設置爲'Pixel',而其他方法則不會。因此,DPI設置被忽略,而其他方法可能使用「Point」,因此需要考慮圖像DPI。 – Jens

相關問題