1

I want to draw the text on Bitmap and I did it with the summary code below

BITMAPINFO bitmapInfo;
bitmapInfo.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
bitmapInfo.bmiHeader.biWidth = _imgWidth;
bitmapInfo.bmiHeader.biHeight = _imgHeight;
bitmapInfo.bmiHeader.biPlanes = 1;
bitmapInfo.bmiHeader.biBitCount = 24;
bitmapInfo.bmiHeader.biCompression = BI_RGB;
bitmapInfo.bmiHeader.biSizeImage = 0;

HDC hdc = GetDC(NULL);
if (hdc == NULL)
    return false;

HFONT hFont = CreateFont( 50, 0, 0, 0, FW_BOLD, 0, 0, 0, DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, 0, DEFAULT_QUALITY, DEFAULT_PITCH | FF_DONTCARE, "Arial" );
if(hFont == NULL)
    return false;

HBITMAP hBitmap = CreateDIBitmap(hdc, (LPBITMAPINFOHEADER) &bitmapInfo.bmiHeader, CBM_INIT, _BRG24arrayIn, (LPBITMAPINFO) &bitmapInfo, DIB_RGB_COLORS);
if(hBitmap == NULL) 
    return false;

HDC hMemDC = CreateCompatibleDC(hdc);
if (hMemDC == NULL)
    return false;

HBITMAP hBitmapOld = (HBITMAP)SelectObject(hMemDC, hBitmap);
if( hBitmapOld == NULL )
    return false;

HFONT hFontOld = (HFONT)SelectObject(hMemDC, hFont);
if ( hFontOld == NULL )
    return false;

SetBkMode(hMemDC, TRANSPARENT);
SetTextColor(hMemDC, 0x0000FF00);
RECT rect;
SetRect(&rect, 0, 0, _imgWidth, _imgHeight); 

if (DrawText(hMemDC, "11:41:33", -1, &rect, DT_TOP|DT_LEFT) == 0)
    return false;

GetDIBits(hdc, hBitmap, 0, _imgHeight, _BRG24arrayOut, (LPBITMAPINFO)&bitmapInfo, DIB_RGB_COLORS);
return true;

The text that I want to draw is "11:41:33" and text alignment is DT_TOP|DT_LEFT

But the result is the text is rotated and occurred on the LEFT-BOTTOM as result image below

enter image description here

The input array _BRG24arrayIn is in BRG24 format, someone can tell me what happen?

Many thanks,

T&TGroup!

Jonathan Potter
  • 36,172
  • 4
  • 64
  • 79
TTGroup
  • 3,575
  • 10
  • 47
  • 79
  • 2
    It isn't rotated, it is upside-down. That tends to happen with bitmaps, they are normally stored inverted with the last scanline at the start of the bitmap. It isn't clear what you do past this code that makes that implementation detail visible. Using GDI+ is the better mousetrap to avoid these kind of accidents. – Hans Passant Jun 16 '13 at 11:51
  • Thank Hans Passant! Many people use this code to draw text on bitmap, and I didn't find anyone who met this problem yet, can you show me how to fix this code without using GDI+? – TTGroup Jun 16 '13 at 11:56
  • 1
    I don't know if it needs fixing, I think you are doing something wrong after this code. Like the way you display or save it. Nor would I ever write code like this, GDI+ is *way* easier. So no, I can't show you. – Hans Passant Jun 16 '13 at 12:03

1 Answers1

3

You need to negate the height in the BITMAPINFOHEADER structure to get a top-down bitmap (i.e. one where row 0 is at the top rather than the bottom). For example:

bitmapInfo.bmiHeader.biHeight = -_imgHeight;
Jonathan Potter
  • 36,172
  • 4
  • 64
  • 79