zoukankan      html  css  js  c++  java
  • [C#]GDI+中使用BitBlt绘制图像到窗口失败

      代码如下,将一张图绘制到窗口上,结果只有一个全黑的矩形:

    1 Bitmap bmp = (Bitmap)Bitmap.FromFile(@"C:\Users\Ken\Desktop\Load2.bmp"); 
    2 Graphics grDest = Graphics.FromHwnd(pictureBox1.Handle);
    3 Graphics grSrc = Graphics.FromImage(bmp);
    4 IntPtr hdcDest = grDest.GetHdc();
    5 IntPtr hdcSrc = grSrc.GetHdc();
    6 BitBlt(hdcDest, 0, 0, pictureBox1.Width, pictureBox1.Height,
    7 hdcSrc, 0, 0, (uint)TernaryRasterOperations.SRCCOPY); // 0x00CC0020
    8 grDest.ReleaseHdc(hdcDest);
    9 grSrc.ReleaseHdc(hdcSrc);

      在这里,我将Image绘制到Graphics上,不使用DrawImage,是想使用BitBlt的Raster-Operation能力,具体来说,我手里有两张图,其中一张是掩色,需要先And再Or的操作,所以必须使用GDI的BitBlt。

      解决方案: 

     1 using (Bitmap bmp = (Bitmap)Bitmap.FromFile(@"C:\Jason\forest.jpg")) 
    2 using (Graphics grDest = Graphics.FromHwnd(pictureBox1.Handle))
    3 using (Graphics grSrc = Graphics.FromImage(bmp))
    4 {
    5 IntPtr hdcDest = IntPtr.Zero;
    6 IntPtr hdcSrc = IntPtr.Zero;
    7 IntPtr hBitmap = IntPtr.Zero;
    8 IntPtr hOldObject = IntPtr.Zero;
    9 try
    10 {
    11 hdcDest = grDest.GetHdc();
    12 hdcSrc = grSrc.GetHdc();
    13 hBitmap = bmp.GetHbitmap();
    14 hOldObject = SelectObject(hdcSrc, hBitmap);
    15 if (hOldObject == IntPtr.Zero)
    16 throw new Win32Exception();
    17 if (!BitBlt(hdcDest, 0, 0, pictureBox1.Width, pictureBox1.Height, hdcSrc, 0, 0, 0x00CC0020U))
    18 throw new Win32Exception(); }
    19 finally
    20 {
    21 if (hOldObject != IntPtr.Zero) SelectObject(hdcSrc, hOldObject);
    22 if (hBitmap != IntPtr.Zero) DeleteObject(hBitmap);
    23 if (hdcDest != IntPtr.Zero) grDest.ReleaseHdc(hdcDest);
    24 if (hdcSrc != IntPtr.Zero) grSrc.ReleaseHdc(hdcSrc);
    25 }
    26 }

      也就是说,在BitBlt之前,先将和Graphics有联系的Bitmap选作DC的背景图。

      猜测,使用Graphics.FromImage的时候,.Net底层并没有将Bitmap对应的HBitmap选入HDC而只是将两个.Net对象联系起来了,而后在DrawImage中有两次SelectObject分别选入和选出以在HBitmap上绘图。所以独立于.Net进行GDI操作的时候,需要在GDI层面再将两者联系起来,使用SelectObject。

  • 相关阅读:
    DB2 SQL1477N问题
    db2 查看表空间使用率
    DB2中的数据类型
    DB2锁机制
    DB2数据库常用命令数据库学习
    DB2 sql报错后查证原因与解决问题的方法
    F. Bakkar In The Army 二分
    On the way to the park Gym
    csu 1552: Friends 二分图 + Miller_Rabin
    Gym
  • 原文地址:https://www.cnblogs.com/cbscan/p/2109057.html
Copyright © 2011-2022 走看看