How to stroke text when drawing it with DrawString function in GDI+? - c++

There's a GDI's StrokePath API that can allow to simulate "stroking" of text using this method. I'll copy it here:
void CCanvas::DrawOutlineText( CDC& dc, const CString& Text )
{
const int RestorePoint = dc.SaveDC();
// Create new font
CFont NewFont;
NewFont.CreatePointFont( 700, TEXT( "Verdana" ), &dc );
// Use this font
dc.SelectObject( &NewFont );
// Brush for pen
LOGBRUSH lBrushForPen = { 0 };
lBrushForPen.lbColor = RGB( 200, 150, 100 );
lBrushForPen.lbHatch = HS_CROSS;
lBrushForPen.lbStyle = BS_SOLID;
// New pen for drawing outline text
CPen OutlinePen;
OutlinePen.CreatePen( PS_GEOMETRIC | PS_SOLID, 2, &lBrushForPen, 0, 0 );
// Use this pen
dc.SelectObject( &OutlinePen );
dc.SetBkMode( TRANSPARENT );
dc.BeginPath();
// This text is not drawn on screen, but instead each action is being
// recorded and stored internally as a path, since we called BeginPath
dc.TextOut( 20, 20, Text );
// Stop path
dc.EndPath();
// Now draw outline text
dc.StrokePath();
dc.RestoreDC( RestorePoint );
}
In my case I'm using DrawString function from GDI+ to draw text.
Does anyone know if there's an alternative to BeginPath, EndPath and StrokePath in GDI+ to simulate text stroking?
EDIT: Following the advice by jschroedl below, I tried the following:
CString str = L"Text";
Graphics grpx(dc.GetSafeHdc());
SolidBrush gdiBrush(Color(0xFF, 0xFF, 0, 0));
StringFormat gdiSF;
gdiSF.SetAlignment(StringAlignmentNear);
gdiSF.SetFormatFlags(StringFormatFlagsNoWrap | StringFormatFlagsNoFitBlackBox |
StringFormatFlagsNoFontFallback | StringFormatFlagsNoClip);
gdiSF.SetHotkeyPrefix(HotkeyPrefixNone);
gdiSF.SetTrimming(StringTrimmingNone);
grpx.SetTextRenderingHint(TextRenderingHintAntiAlias);
grpx.SetPixelOffsetMode(PixelOffsetModeNone);
grpx.SetInterpolationMode(InterpolationModeHighQualityBicubic);
GraphicsPath dd;
FontFamily gdiFF(L"Segoe UI");
const PointF pntF(0, 0);
dd.AddString(str, str.GetLength(), &gdiFF, FontStyleRegular, 58.0f, pntF, &gdiSF);
Pen penFF(Color(0xFF, 0xFF, 0, 0), 1.0f);
grpx.DrawPath(&penFF, &dd);
that produced quite a jagged outline (enlarged screenshot):
Any idea how to make it render with anti-aliasing?

I believe our code creates a GraphicsPath object, calls GraphicsPath::AddString() to get the path for the text and later draws the path with Graphics::DrawPath().
Update:
Based on the blocky text, I experimented and think this looks a bit smoother.
grpx.SetTextRenderingHint(TextRenderingHintClearTypeGridFit);
grpx.SetSmoothingMode(SmoothingModeHighQuality);
grpx.SetPixelOffsetMode(PixelOffsetModeHalf);

Related

Underline is drawn outside of rectangle reported by DrawText with DT_CALCRECT

Symptoms
I'm having an issue with the recent version 2.0 of the Lato font in its "Regular" variant. This issue doesn't appear with Lato 1.0.
It seems that the underline is drawn 1px below the rectangle reported by DrawText() with the DT_CALCRECT flag.
In the following screenshots the calculated rectangle is indicated by the blue background. I've added 10px to the right of this rectangle so you can see the discrepancy to the position where the underline is drawn.
Lato 2.0 - underline is incorrectly drawn outside of rectangle reported by DT_CALCRECT:
Lato 1.0 - underline is correctly drawn inside of rectangle reported by DT_CALCRECT:
MCVE
can be reproduced on Win 10 and Win 7 (Win 8 not tested)
Download and install the Lato 2.0 Regular font (Lato-Regular.ttf).
Create a dialog based MFC application using the wizard and replace the OnPaint() handler of the dialog with the sample code.
Sample code for OnPaint():
CPaintDC dc{ this };
CRect rect; GetClientRect( &rect );
LOGFONTW lf{};
wcscpy_s( lf.lfFaceName, L"Lato" );
lf.lfHeight = 20 * 10; // tenths of a point
lf.lfWeight = FW_NORMAL;
lf.lfUnderline = TRUE;
CFont font;
VERIFY( font.CreatePointFontIndirect( &lf ) );
const int saved = dc.SaveDC();
dc.SelectObject( &font );
dc.SetBkMode( TRANSPARENT );
dc.SetTextColor( RGB( 0, 0, 0 ) );
const CString text = L"Hello Lato";
const DWORD dtFlags = 0;
// Calculate the size required by the text and fill this rectangle
CRect textRect = rect;
dc.DrawText( text, textRect, dtFlags | DT_CALCRECT );
textRect.right += 10;
dc.FillSolidRect( 0, 0, textRect.right, textRect.bottom, RGB( 180, 180, 255 ) );
// Actually draw the text
dc.DrawTextW( text, rect, dtFlags );
if( saved )
dc.RestoreDC( saved );
Question
Do you think this is an issue in my code, a bug in the OS or a bug in the font?
Unfortunately I can't just use Lato 1.0 as Lato 2.0 added support for many new languages my software needs to support.

CClientDC and DC not Drawing on ChtmlEditCtrl

Hi all I am working with a CHtmlEditCtrl in MFC. I want to draw some random rectangles and lines inside a function handling right click event.
The ChtmlEditCtrl control is created from static using this snippet:
bool CHtmlEditCtrlEx::CreateFromStatic( UINT nID, CWnd* pParent ) {
CStatic wndStatic;
if ( !wndStatic.SubclassDlgItem(nID, pParent)) {
return false;
}
CRect rc;
wndStatic.GetWindowRect( &rc );
pParent->ScreenToClient( &rc );
if (Create( 0, (WS_CHILD | WS_VISIBLE), rc, pParent, nID, 0 )) {
...
}
Then I override the CWnd::pretranslate() function as thus:
CClientDC dcc(this);
switch (pMsg->message) {
case WM_RBUTTONUP: // Right-click
// Just some dummy values
DrawSquigly(dcc, 600, 240, 20);
break;
}
the DrawSquigly() function is defined as thus:
void CHtmlEditCtrlEx::DrawSquigly(CDC &dcc, int iLeftX, int iWidth, int iY)
{
CAMTrace trace;
trace.Trace("Drawing Squiggly");
//dcc.TextOut(10, 10, CString(_T("I used a client DC!")));
CPen * oldPen;
CBrush * oldBrush;
oldPen = (CPen *) dc.SelectStockObject(WHITE_PEN);
dcc.MoveTo(5,10);
dcc.LineTo(80, 10);
dcc.SelectObject(oldPen);
//GDI 002_2: Create custom pen with different Line thickness.
CPen thick_pen(PS_SOLID, 3, RGB(0,255,0));
oldPen = dc.SelectObject(&thick_pen);
dcc.MoveTo(5, 20);
dcc.LineTo(80,20);
dcc.SelectObject(oldPen);
//GDI 002_3: Create a Rectangle now
dcc.Draw3dRect(5,30,80,70, RGB(25,25,255), RGB(120,120,120));
//GDI 002_4: Create a Brush that we can use for filling the
// closed surfaces
CBrush brush(RGB(255,0,255));
oldBrush = dc.SelectObject(&brush);
dcc.Rectangle(5,110,80,140);
dcc.SelectObject(oldBrush);
//GDI 002_5: Hatch Brush is useful to apply a pattern in stead
//of solid fill color
CBrush* hatBrush = new CBrush();
hatBrush->CreateHatchBrush(HS_CROSS, RGB(255,0,255));
oldBrush = dc.SelectObject(hatBrush);
dcc.FillRect(new CRect(5,160,80,190), hatBrush);
dcc.SelectObject(oldBrush);
}
but no drawing happens when I right click. I think I am missing something especially because I am new to MFC.
I have added a trace to the top of the event handler to be sure that the function is getting called and it is.
Can anyone please point me the right direction?
There are actually 2 device context in your code: one you pass as parameter in the call (we don't know where it comes from) and the other created locally in the drawing function.
Normally, when the systems gives you a DC it expects you draw something in it, not that you draw into something else.
If the window you are working on is layered, the system gives you a memory context you draw in that is - upon clearing - blit-ted onto the window itself with some window manager effect.
My suspect is that -by allocating a second dc- your drawing are ovewritten when the first one (you left blank) is cleared upon returning from the message handler.

C++ MFC How to Draw Alpha transparent Rectangle

in a C++ MFC application. using the dc of ( CPaintDC dc(this); )
How do i draw a rectangle ( LPRECT ) with an alpha transparency that i can adjust.?
Following is an example c# code which i need to convert into C++
private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
Graphics g = e.Graphics;
Color color = Color.FromArgb(75,Color.Red); //sets color Red with 75% alpha transparency
Rectangle rectangle = new Rectangle(100,100,400,400);
g.FillRectangle(new SolidBrush(color), rectangle); //draws the rectangle with the color set.
}
You need to look into GDI+. Its a bit of a faff but you can create a "Graphics" object as follows:
Gdiplus::Graphics g( dc.GetSafeHdc() );
Gdiplus::Color color( 192, 255, 0, 0 );
Gdiplus::Rect rectangle( 100, 100, 400, 400 );
Gdiplus::SolidBrush solidBrush( color );
g.FillRectangle( &solidBrush, rectangle );
Don't forget to do
#include <gdiplus.h>
and to call
GdiplusStartup(...);
somewhere :)
You'll notice it's pretty damned similar to your C# code ;)
Its worth noting that the 75 you put in your FromArgb code doesn't set 75% alpha it actually sets 75/255 alpha or ~29% alpha.
GDI (and thus MFC) has no decent support for drawing with an alpha. But GDI+ is available in C++ code as well. Use #include <gdiplus.h> and initialize it with GdiplusStartup(). You can use the Graphics class, create one with its Graphics(HDC) constructor from your CPaintDC. And use its FillRectangle() method. The SDK docs are here.
int StartHoriz,StartVert,BarWidth,BarHeight; // rect start, width and height
StartHoriz=0;
StartVert=100;
width = 100;
height=120;
CDC* pCDC = GetDC(); // Get CDC pointer
CRect Rect(StartHoriz,StartVert,BarWidth,BarHeight); //create rectangle dimensions
pCDC->Rectangle(Rect); //draw rectangle

Black border around characters when draw Image to a transparent Bitmap

I have to draw a String on a transparent bitmap at first, then draw A to destination canvas.
However on certain case, there is black border around the characters.
Bitmap* tempImg = new Bitmap(1000, 1000, PixelFormat32bppARGB);
Graphics tempGr(tempImg);
tempGr.Clear(Color(0, 255,255,255));
Gdiplus::SolidBrush* brush = new SolidBrush(Color(255, 255, 0, 0 ));
Gdiplus::FontFamily fontFamily(L"Times New Roman");
Gdiplus::Font* font = new Gdiplus::Font(&fontFamily, 19, FontStyleRegular, UnitPixel);
RectF rec(400, 400, 1000, 10000);
tempGr.DrawString(
L"Merry Chrismas",
-1,
font,
rec,
NULL,
brush
);
Graphics desGr(hdc);
desGr.Clear(Color::Gray);
desGr.DrawImage(tempImg , 0,0, 1000, 1000);
The character draw on desGr have black board for some fontsize.
How can I avoid this problem?
Many thanks!
I think the problem here is that you are drawing the text onto a transparent background.
You could try adding this line after the call to tempGr.Clear...
tempGr.TextRenderingHint = TextRenderingHint.AntiAlias;
ps - sorry not sure the exact syntax in C++ ;)
I just solved this problem in XNA:
Clear background to the same as the foreground color. The only difference is that the background should have Alpha=0, and the foreground with Alpha >> 0
The black border comes from blending of your background and foreground of different colors. Try to clear the background to some contrasting color to fully appreciate the phenomenon.

Small example on getting Cairo graphics to work with MFC?

I have some legacy MFC apps, and I'd like to use the Cairo drawing engine to add some charts and graphs.
I'm searching for a small example of how to get that to work. Basically, once I've created a PNG or GIF file, how do I get that show up in an MFC CView window?
My google-fu is not finding any good clues.
From my demo samples,
// cairo_surface_t *surface;
// cairo_t *cr;
// surface = call_win32_surface_create_with_dib_T(CAIRO_FORMAT_ARGB32, 240, 80);
// cr = call_create_T (surface);
// call_surface_write_to_png_T (surface, "hello.png");
HDC src = call_win32_surface_get_dc_T(surface); // <--------
BitBlt(dest, 0, 0, 240, 80, src, 0,0, SRCCOPY); // <--------
Assuming that you already have a surface you can use something like the above sample.dest is the HDC handle to the window you want to render the cairo surface.
Update: CView::OnDraw()
You should implement the OnDraw() method for your CView (inherited?) class.
You can use the pDC pointer to draw the cairo surface, ie:
pDC->BitBlt(0, 0, 240, 80, src, 0,0, SRCCOPY); // "HDC src" is mentioned above