我正在尝试使用此代码直接在Bitmap
上绘制PictureBox
:
Bitmap bmp = (Bitmap)Bitmap.FromFile(@"C:\Users\Ken\Desktop\Load2.bmp");
Graphics grDest = Graphics.FromHwnd(pictureBox1.Handle);
Graphics grSrc = Graphics.FromImage(bmp);
IntPtr hdcDest = grDest.GetHdc();
IntPtr hdcSrc = grSrc.GetHdc();
BitBlt(hdcDest, 0, 0, pictureBox1.Width, pictureBox1.Height,
hdcSrc, 0, 0, (uint)TernaryRasterOperations.SRCCOPY); // 0x00CC0020
grDest.ReleaseHdc(hdcDest);
grSrc.ReleaseHdc(hdcSrc);
但它不是渲染Bitmap
的内容,而是绘制一个近乎黑色的固体块。我很确定问题出在源hDC上,因为如果我在上面的代码中将SRCCOPY更改为WHITENESS,它会按预期绘制一个纯白色块。
注意:下一个代码段工作正常,因此位图本身没有任何问题:
Bitmap bmp = (Bitmap)Bitmap.FromFile(@"C:\Users\Ken\Desktop\Load2.bmp");
pictureBox1.Image = bmp;
答案 0 :(得分:9)
这是因为设备上下文包含1x1黑色位图,直到使用SelectObject
。无论出于何种原因,Graphics.FromImage
为您提供了与位图兼容的设备上下文,但它不会自动将位图选择到设备上下文中。
以下代码将使用SelectObject
。
当然,如果可能,您应该使用托管的Graphics.DrawImage
代替BitBlt
,但我认为您有充分的理由使用BitBlt
。
private void Draw()
{
using (Bitmap bmp = (Bitmap)Bitmap.FromFile(@"C:\Jason\forest.jpg"))
using (Graphics grDest = Graphics.FromHwnd(pictureBox1.Handle))
using (Graphics grSrc = Graphics.FromImage(bmp))
{
IntPtr hdcDest = IntPtr.Zero;
IntPtr hdcSrc = IntPtr.Zero;
IntPtr hBitmap = IntPtr.Zero;
IntPtr hOldObject = IntPtr.Zero;
try
{
hdcDest = grDest.GetHdc();
hdcSrc = grSrc.GetHdc();
hBitmap = bmp.GetHbitmap();
hOldObject = SelectObject(hdcSrc, hBitmap);
if (hOldObject == IntPtr.Zero)
throw new Win32Exception();
if (!BitBlt(hdcDest, 0, 0, pictureBox1.Width, pictureBox1.Height,
hdcSrc, 0, 0, 0x00CC0020U))
throw new Win32Exception();
}
finally
{
if (hOldObject != IntPtr.Zero) SelectObject(hdcSrc, hOldObject);
if (hBitmap != IntPtr.Zero) DeleteObject(hBitmap);
if (hdcDest != IntPtr.Zero) grDest.ReleaseHdc(hdcDest);
if (hdcSrc != IntPtr.Zero) grSrc.ReleaseHdc(hdcSrc);
}
}
}
[DllImport("gdi32.dll", EntryPoint = "SelectObject")]
public static extern System.IntPtr SelectObject(
[In()] System.IntPtr hdc,
[In()] System.IntPtr h);
[DllImport("gdi32.dll", EntryPoint = "DeleteObject")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool DeleteObject(
[In()] System.IntPtr ho);
[DllImport("gdi32.dll", EntryPoint = "BitBlt")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool BitBlt(
[In()] System.IntPtr hdc, int x, int y, int cx, int cy,
[In()] System.IntPtr hdcSrc, int x1, int y1, uint rop);