当覆盖两个相同大小的图像时,一个是偏移的

时间:2016-01-19 14:22:36

标签: .net vb.net image bitmap gdi+

我试图通过将一个图像叠加在另一个图像上来创建图像。代码有效,但我覆盖的图像似乎有点拉伸,我无法理解为什么。

所以代码只是创建一个空白的红色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

1 个答案:

答案 0 :(得分:4)

您可以使用

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

相反,避免在绘制源图像时进行任何缩放。这有效但我实际上不太确定你的解决方案有什么问题。

Reference Source开始,DrawImageUnscaledAndClipped似乎使用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设置重新调整图像,Matt发现该设置小于默认值96,这会导致图像拉伸:< / p>

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