4

(非托管 C++)我已经成功地将 PNG 文件绘制到可以在桌面上拖动的透明分层窗口,但现在我的问题是在透明分层窗口上绘制文本

这是我的代码和我在中间绘制文本的尝试,重要的是要注意我使用的是 screenDC 而不是使用 WM_PAINT 消息中的那个

[编辑] 评论后更新代码,现在我只是想在获得 HBITMAP 版本之前在位图上写文本,这次我使用的是 DrawString,因为 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. 从位图创建一个 Graphics 对象
  3. 使用 DrawString 将文本写入位图
  4. 处理 Graphics 对象
  5. 使用位图保存方法将结果保存到文件

显然,也可以从 DC 制作图形对象,然后在 DC 上绘制文本,但我再次不知道如何做到这一点

4

1 回答 1

3

整体方法看起来是正确的,但我认为你在DrawString通话中遇到了一些问题。查看MSDN上的文档(尤其是示例) 。

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

可能需要指定第三个、第五个和第六个参数(字体、格式和画笔)。文档没有说它们是可选的。传递NULL这些可能会导致 GDI+ 将调用视为无操作。

第二个参数不应在字符串中包含终止 L'\0'。如果您的字符串始终终止,则使用 -1 可能是最安全的。

于 2011-01-25T18:28:44.467 回答