首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >BitBlt代码不工作

BitBlt代码不工作
EN

Stack Overflow用户
提问于 2010-02-20 22:51:28
回答 1查看 8.8K关注 0票数 4

我正在尝试使用此代码直接在PictureBox上绘制Bitmap

代码语言:javascript
复制
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);

我非常确定问题出在源hDC上,因为如果我在上面的代码中将Bitmap改为白色,它会像预期的那样绘制一个纯白的块。

注意:下面这段代码运行良好,因此位图本身没有任何问题:

代码语言:javascript
复制
Bitmap bmp = (Bitmap)Bitmap.FromFile(@"C:\Users\Ken\Desktop\Load2.bmp");
pictureBox1.Image = bmp;
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2010-02-20 23:24:56

这是因为在使用SelectObject之前,设备上下文包含1x1黑位图。无论出于何种原因,Graphics.FromImage都会为您提供与位图兼容的设备上下文,但它不会自动将位图选择到设备上下文中。

下面的代码将使用SelectObject

当然,如果可能的话,您应该使用托管Graphics.DrawImage而不是BitBlt,但我假设您有充分的理由使用BitBlt

代码语言:javascript
复制
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);
票数 10
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/2302550

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档