Windowsclient Development--How to measure the physical length of a string display

Source: Internet
Author: User
Tags drawtext vector font

The first thing I need to say is that the length of the string I'm talking about is not a string, or a size of string. I mean the length of the display. That is, the physical length.

Reason:
The reason to mention this. is due to a number of problems encountered.
When you use Duilib for development. found that the label control does not have an adaptive width.

Thinking:
This display is a shortage of this library, but we can try to change the library.

But the spirit of open source. Maybe the library was designed to be a label that doesn't fit the width of the string?

All we have to do is take the second path, we first get the width value of the string to display. Then set the width of the label to wide.

Realize:
Now the problem is on Windows. How do I get the width of a string?

This time must have thought of using equipment descriptive narrative table, HDC.

How to get a DC and how to release it. We will not repeat it here. The previous blog has been explained.

This time you will ask, how can I determine the length of a string display?
For the same string. Fonts of different sizes. The display is not the same.

So, we certainly need to use fonts.

Here's a function:

HFONT hFont = CreateFont(27, 0, 0, 0, FW_DONTCARE, 0, 0, 0,        ANSI_CHARSET, OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS,        DEFAULT_QUALITY, DEFAULT_PITCH | FF_DONTCARE, NULL);

Look at this function, there are a lot of parameters:

Cheight is the height of the font.


Cwidth is the width of the font.
Cescapement is the tilt angle of the font.


Corientation is the tilt angle of the font.
Cweight is the weight of the font.


Bitalic is whether the font is italic.
Bunderline is whether the font has an underscore.


Bstrikeout is whether the font has strikethrough.


Icharset is the character set used by the font.
Ioutprecision is to specify how to select the appropriate font.
The iclipprecision is used to determine the precision of the cropping.


Iquality is how to match the chosen font.
Ipitchandfamily is the spacing flag and attribute flags.
Pszfacename is the name of the font.
function function: This function creates a special logical font that can be selected at a later time, regardless of the device.
Function prototypes: Hfont createfont (int nheight, int nwidth, int nescapement, int norientation, int fnweight, DWORD fdwltalic, DWORD FDW Underline, DWORD Fdwstrikeout, DWORD

Fdwcharset, DWORD Fdwoutputprecision, DWORD Fdwclipprecision, DWORD fdwquality, DWORD fdwpitchandfamily, LPCTSTR Lpszface).

Number of references:
Nheight: Specifies the logical unit height of the character cell or character of the font, the height value of the character (also called Em height), which is the character cell height minus the internal header value. The font mapper interprets the value specified by nheight in the following manner, for example. Meaning of each value
For:

0: Font mapper converts this value in device units and matches the cell height of the existing font.

0: The font mapper conversion uses a default height value when selecting a match.

<0: The font mapper converts this value to device units and matches its absolute value to the character height of the existing font.

The font mapper chooses a maximum font size that is not larger than the full height.

This mapping occurs when the font is used for the first time.

For mm_text mapping, you can use the following formula to determine the height of a font that specifies a point size:

Nheight=-muldiv (Pointsize, GetDeviceCaps (HDC, Logpixelsy), 72)

Nwidth: Specifies the average width of the logical units of characters for the requested font. Assuming this value is 0, the font mapper chooses a closest match value, and the closest match value is determined by the absolute value of the difference between the feature factor of the current device and the digitized feature factor of the available font.

Nescapement: Specifies an angle between the shift vector and the x-axis of the device, in a very moderate degree. The shift vector is parallel to the baseline of the body line.

Windows NT: Specifies the shift angle of a string when the graphics device is set to gm_advanced and can be positioned without relying on the character of the string.

When the graphics mode is set to Gm_compatible, nescapement specifies the shift angle and the location angle at the same time, and can set nescapement and norientation to the same value.

Windows 95:nescapement Specifies the shift angle and the location angle at the same time, you can set nescapement and norientation to the same value.

Norientation: Specifies the angle between the baseline of each character and the x-axis of the device.

Fnweight: Specifies the weight of the font between 0 and 1000, such as 400 for the standard body and 700 for the black (thick) body, assuming this value is 0, the default weight is used.

For ease of definition. You can use the following values, for example:

Fw_dontcare:0;fw_thin;100. Fw_extralight;200;fw_ultralight. 200;fw_light. 300;

fw_normal:400;fw_regular;400;fw_medium;500. fw_semibold;600;fw_demibold;600;

Fw_bold:700;fw_extrabold. 800. Fw_ultrabold;800;fw_heavy;900;fw_black. 900.

Fdwitalic: Specifies italic if set to true.

Fdwunderline: If set to True, specifies that the underlined word is full.

Fdwstrikeout: If set to True, strikeout specifies the font.

Fdwcharset: Specifies the character set, the following values are defined in advance:

Ansi_charset; Baltic_charset; Chinesebig5_charset; Default_charset;

Easteurope_charset; Gb2312_charset; Greek_charset; Hangul_charset; Mac_charset; Oem_charset; Russian_charset; Shiftjis_charset;
Symbol_charset; Turkish_charset.
Korea windows:johab_charset.
Middle East Windows:hebrew_charsset; Arabic_charset
Windows:thai_charset Thailand

OEM_CHARSET Specifies the character set associated with the operating system.

The ability to use the Default_charset value to agree on the name and size of the font to fully describe the narrative logical font. Assume that the specified font name does not exist. Regardless of the character set of the font can be substituted for the specified font, so be careful to use default_charset to avoid undesirable results.
There are other character set fonts in the operating system. If an application uses a font of an unknown character set, the application does not attempt to translate or interpret a string written in that font.

This parameter is important in the font mapping process.

To ensure consistent results, specify a special character set.

Assume that a font name is specified in the Lpszface parameter to determine whether the Fdwcharset value matches the font character set specified by Lpszface.
Fdwoutputprecision: Specifies the output precision, the output precision of the output with the required font height, width, character positioning, shift, character spacing and character type matching program. It is preferable to one of the following values:

Out_character_precis; not used.

Out_default_precis: Specifies the default font mapper state.

Out_device_precis: Indicates that the font mapper selects a device font when there are multiple fonts in the system that use the same name in the same font.

Out_outline_prcis: This value in Windows NT indicates that the font mapper is selected from TrueType and other border-based fonts.

Out_raster_precis: Indicates that the font mapper chooses a raster font when there are multiple fonts in the system that use the same name.

Out_string_precis: This value is not used by the word full mapper, but is returned as a value when the scanned font is enumerated.

Out_stroke_precis: This value is not used by the font mapper in Windows NT, but is the return value when TrueType fonts, other border-based fonts, and vector fonts are enumerated.

Windows 95: This value is not used by the font mapper. However, when TrueType fonts or vector fonts are enumerated. As the return value.

Out_tt_only_precis: Indicates that the font mapper is selected only from a TrueType font, and the font mapping returns the default state if no TrueType fonts are installed on the system. 、

Out_tt_precis: Indicates that the font mapper chooses a TrueType font when there are multiple fonts with the same name in the system.

When the operating system contains multiple fonts with the same name as the specified names, the application can use the Out_device_precis,out_raster_precis and Out_tt_precis values to control how the font mapper chooses a font. Like what. Assuming the operating system contains a raster of name symbol and TrueType two fonts, specify OUT_TT_PRECIS to make the font mapper select TrueType mode. Specify OUT_TT_ONLY_PRECIS to have the font mapper select a TrueType font, although this will give the TrueType font a name.

Fdwclipprecision. Specifies the cropping precision. Crop precision defines how to crop a character that is partially out of the clipping area, and it can have one or more of the following values:

Clip_default_precis: Specifies the default cropping state.

Clip_character_precis: Not used.

Clip_stroke_precis: Not used by font mapper. However, when a raster font, vector font, or TrueType font is enumerated, it is returned as a value.

In a Windows environment, for compatibility, this value is always returned when the font is enumerated.

Clip_mask: Not used. Clip_embedded: You must use this flag to use embedded read-only fonts.

Clip_lh_angles: When this value is used. The rotation of all fonts depends on whether the coordinate system is positioned in the left or right direction.

Assuming this value is not used, the device font always rotates counterclockwise, but the rotation of other fonts depends on the orientation of the coordinate system.

To get a lot of other information about the orientation of the coordinate system, refer to the number of orientation.

Clip_tt_always: Not used.

Fdwquality: Point to output quality, output quality defines how the GDI carefully matches the logical font attributes to the actual physical font properties. It is preferable to one of the following values:

Default_quality: The appearance of the font is not important.

Draft_quality: The importance of font appearance is greater than when using proof_quality, the scaling is active for GDI raster fonts, which means that there are multiple font sizes to choose from, but the quality may not be high, assuming it is necessary. Bold, italic, underline, strikeout fonts can be used in a comprehensive style.

Proof_quality: Character quality is more important than exactly matching logical font font attributes. For GDI scan fonts, the zoom scale is active. and select the closest size. While using proof_quality, choosing a font size is not complete

Full match, but the quality of the font is very high and there is no appearance of distortion. If necessary, bold, italic, underline, strikeout fonts can be used in a comprehensive style.

Fdwpitchandfamily: Specifies the font spacing and font family, and the lower-end two-bit character spacing for the specified font. It is preferable to one of the following values:

Default_pitch. Fixed_pitch; Variable_pitch

High-end four-bit specified font family. One of the following values is desirable:

Ff_decorative: Fresh fonts. such as older English.

Ff_dontcare: Do not care or do not know.

Ff_mdern: Stroke width fixed font, with or without liner. such as Pica, Elite and Courier New.

Ff_roman: The font of the stroke width change, with a lined line.

such as Ms Serif.

Ff_script: Designed to look like a handwriting font. such as script and cursive.

Ff_swiss: Stroke width change font, no slash. such as Ms Sans Serif.

An application can combine character spacing and font families with operator or to assign a value to fdwpitchandfamily.

The font family description describes the ordinary appearance of a font when all the exact words are not available. You can use them to specify fonts.

Lpszface: A string pointer ending with/0 that points to the typeface name of the specified font, and the length of the string cannot exceed 32 characters (including character/0). The function enumfontfamilies can be used to enumerate the typeface names of all currently available fonts.

Assuming that lpszface is null or pointing to an empty string, GDI uses the first font that can match other properties.

Return value: Assuming the function call succeeds, the return value is a logical font handle. Assume that the function call failed. The return value is null.

Windows NT: If you want to get a lot of other error messages. Please call the GetLastError function.

Note: When a font is no longer in use. DeleteObject can be used to delete.

To protect the copyrights of vendors who provide fonts to Windows and Windows NT. Win32-based applications always list the exact name of the selected font. Because different systems use different fonts. Do not feel that the chosen font is to

The font to be asked. For example, suppose a font called Palatino is required. But the system does not provide such a font. The font mapper will be replaced with a font that has no name but similar properties.

The system always reports the font name selected by the user.

The next step is to use the SelectObject () function. Choose hdc and font, here SelectObject function does not do too much introduction.

The following is the beginning of the overall. We have two ways.

1 using function GetTextExtentPoint32
function function: This function calculates the height and width of the specified body string.


Function prototypes: BOOL GetTextExtentPoint32 (hdc hdc, LPCTSTR lpstring, int cbstring, lpsize lpsize).
Number of references:
HDC: Device environment handle.
Lpstring: Pointer to the body string. This string does not have to end with a, because cbstring specifies the length of the string.


Cbstring: Points to the number of characters in the string.


Lpsize: A pointer to the size structure in which the size of the string is returned.


Return value: Assuming the function call succeeds, the return value is a non-0 value. Assume that the function call failed. The return value is 0.

2 using function DrawText
Function prototypes
int DrawText (
HDC hdc,//Device description table handle
LPCTSTR lpstring,//string to be drawn
int ncount,//Length of string
LPRECT LPRECT,//Pointer to rectangle structure rect
UINT Uformat//drawing options for body
);

Number of references
hDC
[Enter] the device environment handle.
Lpstring:
[Enter] A pointer to the string to be written. Assuming that the parameter ncount is-1, the string must end with a. Assuming that Uformat includes dt_modifystring, the function can add 4 characters to this string, and the buffer holding the string must be large enough to accommodate the additional characters.
Ncount:
[input] points to the number of characters in the string. Assuming that ncount is-1, the string that lpstring points to is considered to end with a. DrawText will automatically calculate the number of characters.
LpRect:
[input/output] Pointer to the structure RECT, including information about the rectangle in which the text will be placed (in logical coordinates).
Uformat:
[Enter] Specifies the method for formatting text. It can be arbitrarily combined with the following values. Each value descriptive narrative is for example the following:
Dt_calcrect: This parameter is more important and allows the DrawText function to calculate the size of the output text. Assuming that the output text has more than one line, the DrawText function uses the width of the rectangle defined by lprect and extends the bottom of the rectangle to accommodate the last line of the output text. Assuming that the output text has only one row, the DrawText function changes the right edge of the rectangle. To accommodate the last character of the next body line. appear in either case. The DrawText function returns the height of the formatted text. Instead of drawing text.
Dt_center: Specifies that the text is centered horizontally.
Dt_vcenter: Specifies that the text is centered vertically.

This tag is only valid for single-line text output. So it must be used in conjunction with Dt_singleline.
Dt_singleline: Single-line display of text. Both the carriage return and the line feed are constantly on line.

Finally, give the code:

intCalwstringwidth (const std::wstring & name) {HDC HDC =:: GetDC (NULL); Hfont Hfont = CreateFont ( -,0,0,0, Fw_dontcare,0,0,0, Ansi_charset, Out_default_precis, Clip_default_precis, default_quality, Default_pitch |    Ff_dontcare, NULL);    SelectObject (HDC, Hfont); Lpctstrstring= Name.c_str (); SIZEsize= {0}; GetTextExtentPoint32 (HDC,string, _tcslen (string), &size); Rect rect = {0};//::D Rawtext (HDC, String, _tcslen (String), &rect, Dt_calcrect | Dt_noprefix | Dt_singleline);DeleteDC (HDC);//int str_width = Std::abs (rect.right-rect.left);    return size. CX;}

Windowsclient Development--How to measure the physical length of a string display

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.