4

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、ほぼ黒の固体ブロックを描画するだけです。上記のコードで SRCCOPY を WHITENESS に変更すると、予想どおり、真っ白なブロックが描画されるため、問題はソース hDC にあると確信しています。

注: 次のスニペットは問題なく動作するため、ビットマップ自体に問題はありません。

Bitmap bmp = (Bitmap)Bitmap.FromFile(@"C:\Users\Ken\Desktop\Load2.bmp");
pictureBox1.Image = bmp;
4

1 に答える 1

10

これは、SelectObject使用されるまで、デバイス コンテキストに 1x1 の黒のビットマップが含まれているためです。何らかの理由で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);
于 2010-02-20T15:24:55.883 に答える