Introduction
I am working on a kind of CAD-Software and needed a function that was able to rotate text around its center inside a rectangle. Because Windows only provides text rotation around the left-bottom corner of the specified text, I had a problem. I was searching through websites for this piece of code, but I didn't find anything. So I tried it on my own, and this is the code I am using in my program.
First, create a CFont
with the angle of rotation specified in nEscapement
. Let your DC select this font and call the following function:
#include <cmath>
void DrawRotatedText(CDC* pDC, const CString str, CRect rect,
double angle, UINT nOptions = 0)
{
double pi = 3.141592654;
double radian = pi * 2 / 360 * angle;
CSize TextSize = pDC->GetTextExtent(str);
CPoint center;
center.x = TextSize.cx / 2;
center.y = TextSize.cy / 2;
CPoint rcenter;
rcenter.x = long(cos(radian) * center.x - sin(radian) * center.y);
rcenter.y = long(sin(radian) * center.x + cos(radian) * center.y);
pDC->SetTextAlign(TA_BASELINE);
pDC->SetBkMode(TRANSPARENT);
pDC->ExtTextOut(rect.left + rect.Width() / 2 - rcenter.x,
rect.top + rect.Height() / 2 + rcenter.y,
nOptions, rect, str, NULL);
}
License
This article has no explicit license attached to it, but may contain usage terms in the article text or the download files themselves. If in doubt, please contact the author via the discussion board below.
A list of licenses authors might use can be found here.