Direct2D - 模拟颜色键控透明位图

时间:2013-01-30 18:22:54

标签: c++ transparency gdi direct2d

我目前正在更新Windows GDI应用程序以使用Direct2D渲染,我需要通过颜色键控支持“透明”位图以实现向后兼容。

现在我正在使用HWND渲染目标和转换后的WIC位图源(到GUID_WICPixelFormat32bppPBGRA)。到目前为止,我的计划是从转换后的位图Lock()创建一个IWICBitmap,然后处理每个像素,如果它与颜色键匹配,则将其alpha值设置为0。

这似乎有点“蛮力” - 这是接近这个的最佳方法还是有更好的方法?

编辑:为了完整性的利益,这里是我的一个摘录 - 看起来它工作正常,但我愿意接受任何改进!

// pConvertedBmp contains a IWICFormatConverter* bitmap with the pixel 
// format set to GUID_WICPixelFormat32bppPBGRA

IWICBitmap* pColorKeyedBmp = NULL;
HRESULT hr    = S_OK;
UINT    uBmpW = 0;
UINT    uBmpH = 0;

pConvertedBmp->GetSize( &uBmpW, &uBmpH );

WICRect rcLock = { 0, 0, uBmpW, uBmpH };

// GetWIC() returns the WIC Factory instance in this app
hr = GetWIC()->CreateBitmapFromSource( pConvertedBmp, 
                                       WICBitmapCacheOnLoad, 
                                       &pColorKeyedBmp );
if ( FAILED( hr ) ) {
   return hr;
}

IWICBitmapLock* pBitmapLock = NULL;
hr = pColorKeyedBmp->Lock( &rcLock, WICBitmapLockRead, &pBitmapLock );
if ( FAILED( hr ) ) {
   SafeRelease( &pColorKeyedBmp );
   return hr;
}

UINT  uPixel       = 0;
UINT  cbBuffer     = 0;
UINT  cbStride     = 0;
BYTE* pPixelBuffer = NULL;

hr = pBitmapLock->GetStride( &cbStride );
if ( SUCCEEDED( hr ) ) {
   hr = pBitmapLock->GetDataPointer( &cbBuffer, &pPixelBuffer );
   if ( SUCCEEDED( hr ) ) {

      // If we haven't got a resolved color key then we need to
      // grab the pixel at the specified coordinates and get 
      // it's RGB

      if ( !clrColorKey.IsValidColor() ) {
         // This is an internal function to grab the color of a pixel
         ResolveColorKey( pPixelBuffer, cbBuffer, cbStride, uBmpW, uBmpH );
      }

      // Convert the RGB to BGR
      UINT   uColorKey = (UINT) RGB2BGR( clrColorKey.GetRGB() );
      LPBYTE pPixel    = pPixelBuffer;

      for ( UINT uRow = 0; uRow < uBmpH; uRow++ ) {

         pPixel = pPixelBuffer + ( uRow * cbStride );

         for ( UINT uCol = 0; uCol < uBmpW; uCol++ ) {

            uPixel = *( (LPUINT) pPixel );

           if ( ( uPixel & 0x00FFFFFF ) == uColorKey ) {
              *( (LPUINT) pPixel ) = 0;
           }
           pPixel += sizeof( uPixel );
        }
     }
   }
}

pBitmapLock->Release();

if ( FAILED( hr ) ) {
   // We still use the original image
   SafeRelease( &pColorKeyedBmp );
}
else {
   //  We use the new image so we release the original
   SafeRelease( &pConvertedBmp );
}

return hr;

1 个答案:

答案 0 :(得分:0)

如果您只需要&#34;处理&#34;要渲染它的位图,那么最快的就是GPU。在Direct2D中,有effects(ID2D1Effect)用于简单的位图处理。你可以编写自己的[似乎比较复杂],或者使用built-in effects之一[这很简单]。有一个名为chroma-key (CLSID_D2D1ChromaKey)

另一方面,如果您需要在CPU上进行进一步处理,则会变得更加复杂。您可能最好优化您拥有的代码。