2011-01-24 284 views
4

(非託管C++) 繪製文本我已經成功繪製PNG文件,我可以在桌面拖動一個透明分層窗口,但現在我的問題是在透明分層窗口繪製文本C++ GDI +的透明分層窗口

這裏是我的代碼和我在中間繪製文本的嘗試,需要注意的是我使用的screenDC而不是使用一個在WM_PAINT消息是很重要的

[編輯]的意見後 更新的代碼,現在我'只是試圖在獲取HBITMAP版本之前在位圖上寫入文本,這一次我需要使用 我正在使用DrawString becau SE的TextOut()不是GDI +,我希望的DrawString真的是GDI +洛爾 仍然沒有工作,雖然,不知道我在做什麼錯

void Draw() // draws a frame on the layered window AND moves it based on x and y 
{ 
    HDC screenDC(NULL); // grab screen 
    HDC sourceDC(CreateCompatibleDC(screenDC)); 

    POINT pos = {x,y}; // drawing location 
    POINT sourcePos = {0,0}; // top left of image 
    SIZE size = {100,100}; // 100x100 image 

    BLENDFUNCTION blendFunction = {0}; 
    HBITMAP bufferBitmap = {0}; 
    Bitmap* TheBitmap = crnimage; // crnimage was already loaded earlier 

    // ------------important part goes here, my attempt at drawing text ------------// 

Gdiplus::Graphics  Gx(TheBitmap); 

// Font* myFont = new Font(sourceDC); 
Font myFont(L"Arial", 16); 


RectF therect; 
therect.Height = 20; 
therect.Width = 180; 
therect.X = 0; 
therect.Y = 0; 

StringFormat format; 
format.SetAlignment(StringAlignmentCenter); 
format.GenericDefault(); 
Gdiplus::SolidBrush GxTextBrush(Gdiplus::Color(255, 255, 0,255)); 


WCHAR thetext[] = L"Sample Text"; 

int stats = Gx.DrawString(thetext, -1, &myFont, therect, &format, &GxTextBrush); 
if(stats) // DrawString returns nonzero if there is an error 
    msgbox(stats); 
stats = Gx.DrawRectangle(&Pen(Color::Red, 3), therect); 
// the rectangle and text both draw fine now 

// ------------important part goes here, my attempt at drawing text ------------// 

    TheBitmap->GetHBITMAP(0, &bufferBitmap); 
    HBITMAP oldBmpSelInDC; 
    oldBmpSelInDC = (HBITMAP)SelectObject(sourceDC, bufferBitmap); 

    // some alpha blending 
    blendFunction.BlendOp = AC_SRC_OVER; 
    blendFunction.SourceConstantAlpha = wndalpha; 
    blendFunction.AlphaFormat = AC_SRC_ALPHA; 
    COLORREF colorKey(RGB(255,0,255)); 
    DWORD flags(ULW_ALPHA); 

    UpdateLayeredWindow(hWnd, screenDC, &pos, & size, sourceDC, &sourcePos, 
    colorKey, &blendFunction, flags); 

    // release buffered image from memory 
    SelectObject(sourceDC, oldBmpSelInDC); 
    DeleteDC(sourceDC); 
    DeleteObject(bufferBitmap); 

    // finally release the screen 
    ReleaseDC(0, screenDC); 
} 

我一直在努力寫我的分層窗口上的文本我知道有幾種方法可以去做 (很遺憾,我不知道如何)

我看到的常見選項是在位圖上繪製文本,然後渲染位圖本身

  1. 使用GDI +加載一個位圖
  2. 創建從位圖
  3. 使用的DrawString一個圖形對象寫入文本位圖
  4. 處置Graphics對象
  5. 使用位圖保存方法來保存結果文件

顯然,人們還可以使圖形從DC對象,然後畫上了DC的文字,而我又沒有線索如何做到這一點

+1

TextOut後的UpdateLayeredWindow調用將立即擦除文本。確實非常重要的是,您只需繪製WM_PAINT消息處理程序。我看不到你繞過這個的原因。 – 2011-01-24 16:46:25

+0

除了Hans所說的外,`TextOut`是一個GDI函數,而不是GDI +,並且對透明度一無​​所知。所以它會創建與DC背景顏色混合的文本,而不是任何應該顯示的內容。 – 2011-01-24 19:17:00

回答

2

總體方法看起來不錯,但我認爲你在撥打DrawString時遇到了一些問題。查看MSDN上的文檔(特別是樣本)。

Gx.DrawString(thetext, 4, NULL, therect, NULL, NULL) 

可能需要指定第三,第五和第六個參數(字體,格式和畫筆)。文檔沒有說它們是可選的。爲這些傳遞NULL可能會導致GDI +將該呼叫視爲無操作。

第二個參數不應在字符串中包含終止L'\ 0'。如果字符串總是終止,那麼使用-1可能是最安全的。