2008. 11. 3. 15:00

Drawing text at an angle

There is another way to draw anything (not only text), rotatet at a specified 
angle. This method is more difficult, but better, because allows you: 

1. Use standard font object (used in COM-based applications, IFontDisp 
interface), which donesn't support rotated fonts; 
2. Draw multiline strings rotated at an angle. 

The trick is to make DC's world transformation. This method is very stable 
and useful. 

Here is sample code: 

///////////////////////////////// 
// Function draws rotated text 
// hdc - Device Context where to draw 
// rctg - Rectangle in which to draw 
// Angle - angle at which the text to be drawn 
// ptrStr - text string 
// 
//////////////////////////////// 
void DrawRotatedText(HDC hdc, RECT *rctg, double Angle , LPCSTR ptrStr, UINT 
uFormat) 

// Height and width of Text Rectangle 
double wdt = rctg->right-rctg->left; 
double hgt = rctg->bottom-rctg->top; 

// Coordinates of Center 
int cx = int(-rctg->left-wdt/2); 
int cy = int(-rctg->top-hgt/2); 

// Transformation Structure 
XFORM xfrm; 

// Changing graphics mode and saving old transformation 
XFORM oldXfrm; 
int grmde = GetGraphicsMode(hdc); 
SetGraphicsMode(hdc,GM_ADVANCED); 
GetWorldTransform(hdc,&oldXfrm); 


// Transformation... 
float cosA =(float)cos(3.1416*Angle/180); 
float sinA =(float)sin(3.1416*Angle/180); 
xfrm.eM11 = cosA/*Zoom/100*/; 
xfrm.eM12 = sinA; 
xfrm.eM21 = -sinA; 
xfrm.eM22 = cosA/*Zoom/100*/; 
xfrm.eDx = (cx*cosA-cy*sinA)-cx; 
xfrm.eDy = (cx*sinA+cy*cosA)-cy; 

SetWorldTransform(hdc,&xfrm); 

////////////// DRAWING TEXT /////////////// 
DrawText( 
hdc, 
ptrStr, 
strlen(ptrStr), 
rctg, 
uFormat 
); 

// Returning old transformation and graphics mode 
SetGraphicsMode(hdc,GM_ADVANCED); 
SetWorldTransform(hdc,&oldXfrm);