Simple Text Rotation






4.27/5 (13 votes)
Sep 27, 2000

139073
A simple function to rotate text around its center point within a rectangle
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>
// pDC : pointer to your device-context
// str : the text
// rect: the rectangle
// nOptions: can be a combination of ETO_CLIPPED and ETO_OPAQUE
// (see documentation of ExtTextOut for more details)
void DrawRotatedText(CDC* pDC, const CString str, CRect rect,
double angle, UINT nOptions = 0)
{
// convert angle to radian
double pi = 3.141592654;
double radian = pi * 2 / 360 * angle;
// get the center of a not-rotated text
CSize TextSize = pDC->GetTextExtent(str);
CPoint center;
center.x = TextSize.cx / 2;
center.y = TextSize.cy / 2;
// now calculate the center of the rotated text
CPoint rcenter;
rcenter.x = long(cos(radian) * center.x - sin(radian) * center.y);
rcenter.y = long(sin(radian) * center.x + cos(radian) * center.y);
// finally draw the text and move it to the center of the rectangle
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.