Visual C ++ achieves special effects on various types of texts

Source: Internet
Author: User
Tags drawtext textout
Generally, programmers want their programs to be beautiful and generous. To meet this requirement, they want to do their best to beautify their programs. On the other hand, text is an indispensable way to transmit information on the program interface. It is a good choice to add and display texts with special effects in appropriate places on the interface, you can get twice the result with half the effort. This example describes how to achieve this goal by writing a simple small program to solve the special display effect of text in Visual C ++. Readers can apply this method to their own programs with slight changes.


Figure 1 surround display of a string

Figure 2. 3D text Effect

  I. Implementation Method

Before describing the various Processing Effects of text, we will first introduce the CFont class provided by MFC in Visual C ++ for creating fonts. For Windows developers, there are two types of fonts that can be created: Inventory fonts (this font can be selected directly by selecting the device context using the font index, for example: CDC :: createStockObject (int nIndex) and Custom font.

The CFONT class is derived from CgdiObject. You can use functions such as Createfont () and CreateFontIndirect () to create a custom font. The two function prototypes are as follows:

Cfont: createfontindirect (const logfont * lplogfont );
Cfont: createfont (INT nheight, int nwidth, int nescapement, int norientation, int nweight, byte bitalic, byte bunderline, byte bytes, byte ncharset, byte noutprecision, byte nclipprecision, byte nquality, byte npitchandfamily, lpctstr lpszfacename ).

The parameters of the second function have a one-to-one relationship with the components of the LOGFONT parameters in the first function. The LOGFONT structure mainly defines the font attributes, which can be found through the help of MSDN:

Typedef struct taglogfont {
Long lfheight; // Character Font height;
Long lfwidth; // The average character width;
Long lfescapement; // The clockwise rotation angle of the text line;
Long lforientation; // font angle;
Long lfweight; // font width;
Byte lfitalic; // skew;
Byte lfunderline; // underline;
Byte lfstrikeout; // deletes a line;
......
} Logfont;

When setting the LOGFONT structure, several member variables such as lfOutPrecision, lfClipPrecision, lfQuality, and lfPitchAndFamily can be set as follows without modification:

Logfont lf; // lf defines font attributes
Lf. lfoutprecision = out_stroke_precis;
Lf. lfclipprecision = clip_stroke_precis;
Lf. lfquality = draft_quality;
Lf. lfPitchAndFamily = VARIABLE _
PITCH | FF_MODERN;

Other member variables should be set according to actual needs. For example, you can use the following settings for bold and incircle Chinese characters that do not have underscores or strikethrough and are not skewed:

Lf. lfHeight = 50;
Lf. lfWidth = 0;
Lf. lfEscapement = 0;
Lf. lfOrientation = 0;
Lf. lfWeight = FW_HEAVY;
Lf. lfItalic = FALSE;
Lf. lfUnderline = FALSE;
Lf. lfStrikeOut = FALSE;
Lf. lfCharSet = GB2312_CHARSET; strcpy (lf. lfFaceName, "");

(1) display skewed text

Figure 1 above shows how to achieve the effect of Surround display by displaying a series of skewed strings. The following describes how to achieve this effect in detail.

It is actually easy to achieve the above results. As long as you use the CFONT class and LOGFONT structure to flexibly create fonts and set the font attributes, you can achieve the effects of skewed text. The LOGFONT structure contains all the information in the font to be created. The ifEscapement Member specifies the angle of the created font and the horizontal direction, it should be noted that the angle of the member variable is in the unit of tenth rather than the degree. For example, if ifEscapement is defined as 450, it indicates that the tilt angle of the font is 45 degrees. To ensure that all fonts are rotated in one direction, you must set the CLIP_LH_ANGLES bit of ifEscapenent. Otherwise, the font may be rotated in the opposite direction.

Just like using other GDI (graphical user interface) objects, You must select the font you have created into the DC (device context) before using the font you have defined ).

(2) 3D text

The computer screen is a two-dimensional plane. The reason why we can enjoy a real 3D image is that the visual illusion is generated by the human eyes due to the different gray colors displayed on the computer screen, the two-dimensional computer screen is perceived as a three-dimensional image. Based on the Color learning knowledge, the protruding part of the three-dimensional object edge is generally high brightness, while the concave part is dark due to the occlusion of the light. This recognition is widely used in drawing buttons and 3D lines on webpages or other applications. It is also applicable to the 3D text to be drawn in this article, that is, the High Brightness color is displayed in the original position, and its contour is outlined in the lower left or upper right corner with a low brightness color, in this way, 3D text is visually displayed. In specific implementation, two 2D texts of different colors can be drawn in different positions using the same font, as long as the coordinates of the two texts are appropriate, in this way, you can visually produce 3D texts with different effects.

The specific implementation idea is to use CDC: SetTextColor () to set the text color to the highlighted (3 DHILIGHT) and shadow (3 DSHADOW) state to display the text; at the same time, note that when you display text twice, you must stagger several pixels to achieve the expected effect. The effect is shown in Figure 2 above.

(3) gradient effect of Text

To achieve the gradient effect of the text, you need to set a timer (using the settimer () function). During the timer response function processing, you can call the CDC: settextcolor () the function constantly changes the display color of the text in the device context to achieve the gradient effect of the text. The text color is the final result of the combination of RGB (red, green, and blue) three basic colors. The ranges of the RGB three colors are (0,255 ), R = G = B, the color effect is gray, the so-called gray, is a transitional color between pure white and pure black, when r = G = B = 0, the color is black. When r = G = B = 255, the color is pure white. You can define a correction variable to continuously increment or decrease the three base colors, to achieve gradient display of text. Here, we only provide implementation ideas. Readers can easily implement the Code themselves.

(4) Others

In addition, you can set a path object to outline a common text, so that it has a special effect. PATH is a newly added GDI object in Win32. Next we will talk about it in terms of concept.

1) concept of Path

In Windows 95/NT Win32 operating systems, in addition to the existing bitmap, paint brush, paint brush, Font, color palette and area, a new GDI object: path is added. A path is one or more images that can be filled, drawn, or simultaneously drawn and filled. The introduction of paths greatly enriches the Windows Graphics function, so that applications can easily create complex areas, draw and fill irregular graphics. The irregular graph here refers to a graph composed of a straight line and a besell curve (as opposed to a regular graph such as a rectangle, polygon, or an elliptical shape ).

2) path usage

Unlike other original GDI objects, the MFC class library does not specifically use a C ++ class to encapsulate path objects (which may be supported in future versions ). You must call an API function (or a member function in the CDC class) to define and use paths. The path usage process is roughly as follows:

(1) Call the beginpath () function to start the path definition;

(2) Call the GDI plotting function to define the path. in Win32, the GDI plotting functions that can be used to define the path include: anglearc (), arc (), arctochord (), ellipse (), lineto (), textout (), and other functions;

(3) Call endpath () to define the end path of the function;

After the path definition is completed, the defined path is also selected into the device description table. The original path object in the device description table is discarded when the beginpath () function is called to start the path definition.

(4) use a path object.

After the path definition is completed, the application can use the relevant GDI functions to use the path. These functions include drawing the path profile strokepath (), filling the path fillpath (), draw the outline and fill it with strokeandfillpath (), convert the path to the region pathtoregion (), linearly convert the path to flattenpath (), extract the path data getpath (), and broaden the path widenpath () and set the cropping path selectclippath. For more information about how to use these functions, see the SDK documentation.

The following code demonstrates how to implement the font hollow effect.

/// // Application redraw function of the Main Window
Void CMyWnd: OnPaint ()
{
// Obtain the device context handle in the customer zone of the window
CPaintDC dc (this); // change the current font
LOGFONT lf;
Dc. GetCurrentFont ()-> GetLogFont (& lf );
CFont font;
CFont * pOldFont; // Save the font object originally used by the device context
Lf. lfCharSet = 134;
Lf. lfHeight =-150;
Lf. lfHeight =-150;
Lf. lfWidth = 0;
Strcpy (lf. lfFaceName, "");
Font. CreateFontIndirect (& lf );
POldFont = dc. SelectObject (& font );
Dc. SetBkMode (TRANSPARENT); // change the current paint brush
CPen pen (PS_SOLID, 1, RGB (255, 0, 0 ));
CPen * pOldPen;
POldPen = dc. SelectObject (& pen); // start a path
Dc. BeginPath ();
Dc. TextOut (10, 10, "hollow words ");
Dc. EndPath (); // draw the path
Dc. StrokePath ();
// You can use the dc. StrokeAndFillPath () function instead. However, this function uses the current brush to fill the interior of the path.
Dc. SelectObject (pOldFont );
Dc. SelectObject (pOldPen );
}

  Ii. programming steps

1. Start visual c ++ 6.0 to generate a single-document view structure Program (for programs that rotate fonts: Project name viewfont; For programs with 3D effects: Project name 3 dtext );

2. Reload the ondraw (CDC * PDC) function of the application;

3. Add code and compile and run the program;

3. program code

/// // Rotate the font
Void CViewFontView: OnDraw (CDC * pDC)
{
CViewFontDoc * pDoc = GetDocument ();
ASSERT_VALID (pDoc );
// TODO: add draw code for native data here
Cstring STR (_ T ("running a C ++ 6.0 programming instance"); // defines the string to be displayed;
Crect rect;
Getclientrect (& rect );
PDC-> setbkmode (transparent); // set the background to transparent;
PDC-> settextcolor (RGB (100,100,255); // you can specify the displayed text color;
Cfont font;
Logfont stfont; // defines the font structure;
Memset (& stfont, 0, sizeof (stfont); // you can specify the font attributes;
Stfont. lfheight = 30;
Stfont. lfweight = fw_normal;
Stfont. lfclipprecision = clip_lh_angles;
Strcpy (stfont. lffacename, "Arial ");
// The following code uses the view center as the dot and displays the string every 30 degrees on the circumference with a radius of 100;
For (double I = 0; I <3600; I + = 300)
{
Stfont. lfescapement = I; // you can specify the font tilt angle;
Font. createfontindirect (& stfont); // create a font object based on the font structure;
Cfont * oldfont;
Oldfont = PDC-> SelectObject (& font); // select the created font into the device context;
If (I <900)
PDC-> TextOut (rect. left + rect. width)/2 + 100 * cos (I/1800*3.14), rect. top + rect. height ()/2-100 * sin (I/1800*3.14), str );
If (I> = 900 & I <1800)
PDC-> TextOut (rect. left + rect. Width ()/2 + 100 * cos (I/1800*3.14 ),
Rect. top + rect. Height ()/2-100 * sin (I/1800*3.14), str );
If (I> = 1800 & I <2700)
PDC-> TextOut (rect. left + rect. Width ()/2 + 100 * cos (I/1800*3.14 ),
Rect. top + rect. Height ()/2-100 * sin (I/1800*3.14), str );
If (I> = 2700 & I <= 3600)
PDC-> TextOut (rect. left + rect. Width ()/2 + 100 * cos (I/1800*3.14 ),
Rect. top + rect. Height ()/2-100 * sin (I/1800*3.14), str );
PDC-> SelectObject (oldFont); // restores the font of the device context;
Font. DeleteObject (); // Delete the created font;
}
}

//////////////////////////////////////// // Programs for displaying 3D Effects

Void CMy3DTextView: OnDraw (CDC * pDC)
{
CMy3DTextDoc * pDoc = GetDocument ();
ASSERT_VALID (pDoc );
// TODO: add draw code for native data here
CString string;
String = "Visual C ++ 6.0 programming instance ";
CFont m_fontLogo;
M_fontLogo.CreateFont (144, 0, 0, 0,155, FALSE, FALSE, "Arial ");
// Create a font;
PDC-> SetBkMode (TRANSPARENT );
CRect rectText;
GetClientRect (& rectText );
CFont * OldFont = pDC-> SelectObject (& m_fontLogo );
COLORREF OldColor = pDC-> SetTextColor (: GetSysColor (COLOR_3DSHADOW ));
// Shadow status display text;
PDC-> DrawText (string, rectText + CPoint (2, 2), DT_SINGLELINE | DT_LEFT | DT_VCENTER | DT_CENTER );
PDC-> SetTextColor (: GetSysColor (COLOR_3DHILIGHT ));
// The highlighted text;
PDC-> DrawText (string, rectText, DT_SINGLELINE | DT_LEFT | DT_VCENTER | DT_CENTER );
PDC-> SetTextColor (OldColor );
PDC-> SelectObject (OldFont );
M_fontLogo.DeleteObject ();
}

  Iv. Summary

As long as you have mastered the above content, you can use the cfont and logfont structures to create different fonts, and then set the display color, position, and time, I believe that more dynamic effects can be achieved.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.