На главную

On-line справка по Win32 API

Написать письмо
БЕСПЛАТНАЯ ежедневная online лотерея! Выигрывай каждый день БЕСПЛАТНО!
Список всех статей A-B-C-D-E-F-G-H-I-J-K-L-M-N-O-P-Q-R-S-T-U-V-W-X-Y-Z | Скачать Вниз

GetCharacterPlacement



[Now Supported on Windows NT]

The GetCharacterPlacement function retrieves information about a character string, such as character widths, caret positioning, ordering within the string, and glyph rendering. The type of information returned depends on the dwFlags parameter and is based on the currently selected font in the given display context. The function copies the information to the specified GCP_RESULTS structure or to one or more arrays specified by the structure.

DWORD GetCharacterPlacement(

HDC hdc, // handle to device context
LPCTSTR lpString, // pointer to string
int nCount, // number of characters in string
int nMaxExtent, // maximum extent for displayed string
LPGCP_RESULTS *lpResults, // pointer to buffer for placement result
DWORD dwFlags // placement flags
);


Parameters

hdc

Identifies the device context.

lpString

Points to the character string to process.

nCount

Specifies the number of characters in the string.

nMaxExtent

Specifies the maximum extent (in logical units) to which the string is processed. Characters that, if processed, would exceed this extent are ignored. Computations for any required ordering or glyph arrays apply only to the included characters. This parameter is used only if the GCP_MAXEXTENT value is given in the dwFlags parameter. As the function processes the input string, each character and its extent is added to the output, extent, and other arrays only if the total extent has not yet exceeded the maximum. Once the limit is reached, processing will stop.

lpResults

Points to a GCP_RESULTS structure that receives the results of the function.

dwFlags

Specifies how to process the string into the required arrays. This parameter can be one or more of the following values:

Value Meaning
GCP_CLASSIN Specifies that the lpClass array contains preset classifications for characters. The classifications may be the same as on output. If the particular classification for a character is not known, the corresponding location in the array must be set to zero. for more information about the classifications, see GCP_RESULTS. This is useful only if GetFontLanguageInfo returned the GCP_REORDER flag.
GCP_DIACRITIC Determines how diacritics in the string are handled. If this value is not set, diacritics are treated as zero-width characters. For example, a Hebrew string may contain diacritics, but you may not want to display them. Use GetFontLanguageInfo to determine whether a font supports diacritics. If it does, you can use or not use the GCP_DIACRITIC flag in the call to GetCharacterPlacement, depending on the needs of your application.
GCP_DISPLAYZWG For languages that need reordering or different glyph shapes depending on the positions of the characters within a word, nondisplayable characters often appear in the codepage. For example, in the Hebrew codepage, there are Left-To-Right and Right-To-Left markers, to help determine the final positioning of characters within the output strings. Normally these are not displayed and are removed from the lpGlyphs and lpDx arrays. You can use the GCP_DISPLAYZWG flag to display these characters.
GCP_GLYPHSHAPE Specifies that some or all characters in the string are to be displayed using shapes other than the standard shapes defined in the currently selected font for the current code page. Some languages, such as Arabic, cannot support glyph creation unless this value is given. As a general rule, if GetFontLanguageInfo returns this value for a string, this value must be used with GetCharacterPlacement.
GCP_JUSTIFY Adjusts the extents in the lpDx array so that the string length is the same as nMaxExtent. GCP_JUSTIFY may only be used in conjunction with GCP_MAXEXTENT.
GCP_JUSTIFYIN Specifies that the lpDx array contains justification weights on input. Normally, a justification weight can be either 0 or 1, where 1 indicates that the width of the given character can be adjusted for justification. For languages in which GetFontLanguageInfo returns the GCP_KASHIDA flag, the justification weight can be one of the GCP_ARAJUST_* values.
GCP_KASHIDA Use Kashidas as well as, or instead of, adjusted extents to modify the length of the string so that it is equal to the value given by nMaxExtent. In the lpDx array, a Kashida is indicated by a negative justification index. GCP_KASHIDA may be used only in conjunction with GCP_JUSTIFY and only if the font (and language) support Kashidas. Use GetFontLanguageInfo to determine whether the current font supports Kashidas.Using Kashidas to justifiy the string can result in the number of glyphs required being greater than the number of characters in the input string. Because of this, when Kashidas are used, the application cannot assume that setting the arrays to be the size of the input string will be sufficient. (The maximum possible will be approximately dxPageWidth/dxAveCharWidth, where dxPageWidth is the width of the document and dxAveCharWidth is the average character width as returned from a GetTextMetrics call).Note that just because GetFontLanguageInfo returns the GCP_KASHIDA flag does not mean that it has to be used in the call to GetCharacterPlacement, just that the option is available.
GCP_LIGATE Use ligations wherever characters ligate. A ligation occurs where one glyph is used for two or more characters. For example, the letters "a" and "e" can ligate to "ж". For this to be used, however , both the language support and the font must support the required glyphs (the example given will NOT be processed by default in English). Use GetFontLanguageInfo to determine whether the current font supports ligation. If it does and a specific maximum is required for the number of characters that will ligate, set the number in the first element of the lpGlyphs array. If normal ligation is required, set this value to zero. If GCP_LIGATE is not given, no ligation will take place. See GCP_RESULTS for more information.If the GCP_REORDER value is usually required for the character set but is not given, the output will be meaningless unless the string being passed in is already in visual ordering (that is, the result that gets put into lpGcpResults->lpOutString in one call to GetCharacterPlacement is the input string of a second call). Note that just because GetFontLanguageInfo returns the GCP_LIGATE flag does not mean that it has to be used in the call to GetCharacterPlacement, just that the option is available.
GCP_MAXEXTENT Compute extents of the string only as long as the resulting extent, in logical units, does not exceed the values given by the nMaxExtent parameter.
GCP_NEUTRALOVERRIDE Certain languages only. Override the normal handling of neutrals and treat them as strong characters that match the strings reading order. Useful only with the GCP_REORDER flag.
GCP_NUMERICOVERRIDE Certain languages only. Override the normal handling of numerics and treat them as strong characters that match the strings reading order. Useful only with the GCP_REORDER flag.
GCP_NUMERICSLATIN Arabic/Thai only. Use standard Latin glyphs for numbers and override the system default. To determine if this option is available in the language of the font, use GetStringTypeEx to see if the language supports more than one number format.
GCP_NUMERICSLOCAL Arabic/Thai only. Use local glyphs for numeric characters and override the system default. To determine if this option is available in the language of the font, use GetStringTypeEx to see if the language supports more than one number format.
GCP_REORDER Reorder the string. Use for languages that are not SBCS and left-to-right reading order. If this value is not given, the string is assumed to be in display order already. If this flag is set for Semitic languages and the lpClass array is used, the first two elements of the array are used to specify the reading order beyond the bounds of the string. GCP_CLASS_PREBOUNDRTL and GCP_CLASS_PREBOUNDLTR can be used to set the order. If no preset order is required, set the values to zero. These values can be combined with other values if theGCPCLASSIN flag is set.If the GCP_REORDER value is not given, the lpString parameter is taken to be visual ordered for languages where this is used, and the lpOutString and lpOrder fields are ignored.Use GetFontLanguageInfo to determine whether the current font supports reordering.
GCP_SYMSWAPOFF Semitic languages only. Specifies that swappable characters are not reset. For example, in a right-to-left string, the '(' and ')' are not reversed.
GCP_USEKERNING Use kerning pairs in the font (if any) when creating the widths arrays. Use GetFontLanguageInfo to determine whether the current font supports kerning pairs.Note that just because GetFontLanguageInfo returns the GCP_USEKERNING flag does not mean that it has to be used in the call to GetCharacterPlacement, just that the option is available. Most TrueType fonts have a kerning table, but you do not have to use it.


It is recommended that an application use the GetFontLanguageInfo function to determine whether the GCP_DIACRITIC, GCP_DBCS, GCP_USEKERNING, GCP_LIGATE, GCP_REORDER, GCP_GLYPHSHAPE, and GCP_KASHIDA values are valid for the currently selected font. If not valid, GetCharacterPlacement ignores the value.
The GCP_NODIACRITICS value is no longer defined and should not be used.

Return Values

If the function succeeds, the return value is the same as the return value from GetTextExtentPoint32, the width and height of the string.
If the function fails, the return value is zero.

Remarks

GetCharacterPlacement ensures that an application can correctly process text regardless of the international setting and type of fonts available. Applications use this function before using the ExtTextOut function and in place of the GetTextExtentPoint32 function (and occasionally in place of the GetCharWidth32 and GetCharABCWidths functions).
Using GetCharacterPlacement to retrieve intercharacter spacing and index arrays is not always necessary unless justification or kerning is required. For non-Latin fonts, applications can improve the speed at which the ExtTextOut function renders text by using GetCharacterPlacement to retrieve the intercharacter spacing and index arrays before calling ExtTextOut. This is especially useful when rendering the same text repeatedly or when using intercharacter spacing to position the caret. If the lpGlyphs output array is used in the call to ExtTextOut, the ETO_GLYPH_INDEX flag must be set.

GetCharacterPlacement checks the lpOrder, lpDx, lpCaretPos, lpOutString, and lpGlyphs members of the GCP_RESULTS structure and fills the corresponding arrays if these members are not set to NULL. If GetCharacterPlacement cannot fill an array, it sets the corresponding member to NULL. To ensure retrieval of valid information, the application is responsible for setting the member to a valid address before calling the function and for checking the value of the member after the call. If the GCP_JUSTIFY or GCP_USEKERNING values are given, the lpDx and/or lpCaretPos members must have valid addresses. Also, the lpDx member must have a valid address if GCP_JUSTIFYIN is given.

When computing justification, if the trailing characters in the string are spaces, the function reduces the length of the string and removes the spaces prior to computing the justification. If the array consists of only spaces, the function returns an error.

See Also

ExtTextOut, GCP_RESULTS, GetCharABCWidths, GetCharWidth32, GetFontLanguageInfo, GetStringTypeEx, GetTextExtentPoint32, GetTextMetrics


Пригласи друзей и счет твоего мобильника всегда будет положительным!
Предыдущая статья
 
Сайт Народ.Ру Интернет
Следующая статья
Пригласи друзей и счет твоего мобильника всегда будет положительным!

GetCharacterPlacement



[Теперь Поддерживанное на Windows NT]

Функция GetCharacterPlacement извлекает информацию о символьной строке, как например, символьная ширина, символ ^ позиционирования, упорядочения в пределах строки, и glyph предоставления. Тип возвращанной информации зависит от параметра dwFlags и находился в к настоящему времени выбранном шрифте в данном дисплейном контексте. Функция копирует информацию в определенную структуру GCP_RESULTS или на одно или более подготавливает определенный структурой.

DWORD GetCharacterPlacement(

HDC hdc, // РУЧКА на устройство контекстного lpString LPCTSTR, // указателя, чтобы нанизывать int nCount, // количеству символов в строке int nMaxExtent, // максимальная степень для отображаемой строки LPGCP_RESULTS *lpResults, // указатель, чтобы буферизоваться для результата размещения DWORD dwFlags // флаги размещения
);


Параметры

hdc

Идентифицирует контекст устройства.

lpString

Точки на символьную строку, чтобы обрабатываться.

nCount

Определяет количество символов в строке.

nMaxExtent

Определяет максимальную степень (на логических устройствах) на которой строка обработана. Символы, что, если обработано, должно превысить эту протяженность проигнорированы. Вычисления для любого необходимого упорядочения или glyph подготавливает относятся только ко включенным символам. Этот параметр используется только если величина GCP_MAXEXTENT дана в параметре dwFlags. Так как функция обрабатывает входную строку, каждый символ и протяженность добавлены к выходу, протяженности, и другое подготавливается только если общая протяженность еще не превысила бы максимум. Как только предел будет достигнут, обрабатывая прекратится.

lpResults

Точки на структуру GCP_RESULTS, которые получают результаты функции.

dwFlags

Определяет как, чтобы обрабатывать строку в необходимый подготавливается. Этот параметр может быть одно или более из следующего величин:

Значение Величины
GCP_CLASSIN Определяет, что массив lpClass содержит инициализировать классификации для символов. Классификации могут быть такими же как и на выходе. Если конкретная классификация для символа не известный, соответствующая позиция в массиве должна быть установлена на zero. более подробно о классификациях, смотри GCP_RESULTS. Это полезное только если GetFontLanguageInfo возвращал бы флаг GCP_REORDER.
GCP_DIACRITIC Определяет как диакритические в строке прооперированы. Если эта величина не установлена, диакритические рассмотрены как нулевые-широтные символы. Например, строка Еврея может содержать диакритические, но Вы не можете хотеть отобразить их. Используйте GetFontLanguageInfo, чтобы определять независимо шрифтовые опоры диакритические. Если это делает, Вы можете использовать или не использовать флаг GCP_DIACRITIC на вызове на GetCharacterPlacement, в зависимости от потребностей вашего приложения.
GCP_DISPLAYZWG Для языков, что нужно переупорядочение или другие glyph формы в зависимости от позиций символов в пределах слова, nondisplayable символы часто появляются в codepage. Например, в codepage Еврея, есть Left-To-Right и маркеры Right-To-Left, чтобы помогать определять конечное позиционирование символов в пределах выходных строк. Нормально эти не отображены и удалены из lpGlyphs и lpDx подготавливается. Вы можете использовать флаг GCP_DISPLAYZWG, чтобы отображать эти символы.
GCP_GLYPHSHAPE Определяет, что некоторые или все символы в строке должны быть отображены используя формы кроме стандартных форм определенных в к настоящему времени выбранном шрифте для текущей кодовой страницы. Некоторые языки, как например, Арабский, не мочь поддержать glyph создание если эта величина не дана. Так как общие правила, если GetFontLanguageInfo возвращает эту величину для строки, эта величина должна быть использована GetCharacterPlacement.
GCP_JUSTIFY Регулирует протяженность в массиве lpDx чтобы длина строки - такой же как и nMaxExtent. GCP_JUSTIFY может только использован в связи (вместе)с GCP_MAXEXTENT.
GCP_JUSTIFYIN Определяет, что массив lpDx содержит вес оправдания на вводе. Нормально, вес оправдания может быть или 0 или 1, где 1 указывает, что ширина данного символа может быть с учетом оправдания. Для языков в которых GetFontLanguageInfo возвращает флаг GCP_KASHIDA, вес оправдания может быть одно из GCP_ARAJUST_* величины.
Использование GCP_KASHIDA Kashidas, а также, или вместо, скорректированная протяженность, чтобы модифицировать длину строки чтобы она равнялась величине данной nMaxExtent. В массиве lpDx, Kashida указан отрицательным индексом оправдания. GCP_KASHIDA может использоваться только в связи (вместе)с GCP_JUSTIFY и только если поддержка шрифта (и языка) Kashidas. Используйте GetFontLanguageInfo, чтобы определять независимо текущие шрифтовые опоры Kashidas.Используя Kashidas, чтобы justifiy строка может закончиться числом glyphs необходимым больше, чем количество символов в входной строке. Из-за этого, когда Kashidas использованы, приложение не может допустить что установка подготавливает, чтобы быть размером входной строки быть достаточным. ( Максимум возможно будет приблизительно dxPageWidth/dxAveCharWidth, где dxPageWidth - ширина документа и dxAveCharWidth - средняя символьная ширина как возвращано с вызова GetTextMetrics).Отметьтесь, что только потому что GetFontLanguageInfo возвращает флаг GCP_KASHIDA не означает, что он должен быть использованн на вызове на GetCharacterPlacement, просто, что опция доступна.
Использование GCP_LIGATE где бы ни символов ligations ligate. ligation Происходит где один glyph использован для двух или больше символов. Например, письма "a" и "e" могут ligate на "ж". Для этого, чтобы быть использованн, тем не менее , оба языка поддерживаются и шрифт должен поддержать необходимые glyphs ( данный пример НЕ обработается по умолчанию в Английском). Используйте GetFontLanguageInfo, чтобы определять независимо текущие шрифтовые опоры ligation. Если это делает и специфический максимум необходим для количества символов, которые будет ligate, установите число в первом элементе массива lpGlyphs. Если нормальный ligation потребовался, установите эту величину в нуль. Если GCP_LIGATE не дан, никакой ligation произойдет. Смотри GCP_RESULTS более подробно.Если величина GCP_REORDER обычно необходима для набора символов но не дана, выход будет бессмысленным если строка, прохоженная в не - уже на визуальном упорядочении (то есть, результат, который получает помещенный в lpGcpResults->lpOutString на одном вызове на GetCharacterPlacement - входная строка вызова секунды). Отметьтесь, что только потому что GetFontLanguageInfo возвращает флаг GCP_LIGATE не означает, что он должен быть использованн на вызове на GetCharacterPlacement, просто, что опция доступна.
GCP_MAXEXTENT Вычисляет протяженность строки только так же долго (длиной) как результирующая протяженность, на логических устройствах, не превышает величины данные параметром nMaxExtent.
Определенные языки GCP_NEUTRALOVERRIDE только. Аннулируйте нормальную обработку нейтральную и обрабатывайте их как прочные символы, которые соответствуют строкам, читающим порядок. Полезный только с флагом GCP_REORDER.
Определенные языки GCP_NUMERICOVERRIDE только. Аннулируйте нормальную обработку числовую и обрабатывайте их как прочные символы, которые соответствуют строкам, читающим порядок. Полезный только с флагом GCP_REORDER.
GCP_NUMERICSLATIN Arabic/Thai только. Используйте стандартное Латинский glyphs для чисел и аннулируйте систему по умолчанию. Для того, чтобы определяться если эта опция доступна на языке шрифта, используйте GetStringTypeEx, чтобы видеть если язык поддерживает более, чем один формат числа.
GCP_NUMERICSLOCAL Arabic/Thai только. Используйте локальные glyphs для числовых символов и аннулируйте систему по умолчанию. Для того, чтобы определяться если эта опция доступна на языке шрифта, используйте GetStringTypeEx, чтобы видеть если язык поддерживает более, чем один формат числа.
GCP_REORDER Преобразовывает строку. Использование для языков, которые - не SBCS и порядок левого права чтения. Если эта величина не дана, строка принята, чтобы быть в дисплейном порядке уже. Если этот флаг установлен для Семитских языков и массив lpClass использован, первые два элемента массива использованы, чтобы определять чтение порядка за границами строки. GCP_CLASS_PREBOUNDRTL и GCP_CLASS_PREBOUNDLTR может быть использован, чтобы устанавливать порядок. Если никакое инициализировать порядок потребовался, установите величины в нуль. Эти величины могут быть объединены другими величинами если флаг theGCPCLASSIN установлен.Если величина GCP_REORDER не дана, lpString параметр потребовался, чтобы быть визуальным заказанным для языков где это использован, и lpOutString и области lpOrder проигнорированы.Используйте GetFontLanguageInfo, чтобы определять независимо текущее шрифтовое переупорядочение опор.
Семитские языки GCP_SYMSWAPOFF только. Определяет, что swappable символы не восстановлены. Например, в левой строке права, '(' и ')' не возобновлены.
Использование GCP_USEKERNING kerning спаривает в шрифте (если имеется) при создании ширины подготавливается. Используйте GetFontLanguageInfo, чтобы определять независимо текущие шрифтовые опоры kerning пары.Отметьтесь, что только потому что GetFontLanguageInfo возвращает флаг GCP_USEKERNING не означает, что он должен быть использованн на вызове на GetCharacterPlacement, просто, что опция доступна. Большинство шрифтов TrueType иметь таблицу kerning, но Вы нет должны использовать это.


Рекомендовано, что прикладное использование функция GetFontLanguageInfo, чтобы определять независимо GCP_DIACRITIC, GCP_DBCS, GCP_USEKERNING, GCP_LIGATE, GCP_REORDER, GCP_GLYPHSHAPE, и величины GCP_KASHIDA быть в силе для к настоящему времени выбранного шрифта. Если не правильный, GetCharacterPlacement игнорирует величину.
Величина GCP_NODIACRITICS больше не определена и не должна использована.

Обратные Величины

Если функция добивается успеха, обратная величина такая же как и обратная величина с GetTextExtentPoint32, ширины и высоты строки.
Если функция терпит неудачу, обратная величина нулевая.

Замечания

GetCharacterPlacement ПРОВЕРЯЕТ, что приложение может правильно обработать тексту независимо от международной установки и типа шрифтов доступных. Приложения используют эту функцию перед использованием функции ExtTextOut и вместо функции GetTextExtentPoint32 (и случайно вместо GetCharWidth32 и функций GetCharABCWidths).
Использование GetCharacterPlacement, чтобы извлекать расстояние intercharacter и индекс подготавливает, не всегда необходимо если оправдание или kerning не потребовалось. Для не-Латинских шрифтов, приложения могут улучшить скорость в которой функция ExtTextOut предоставляет текст используя GetCharacterPlacement, чтобы извлекать расстояние intercharacter и индекс подготавливается перед вызовом ExtTextOut. Это особенно полезное при предоставлении того же текста многократно или при использовании расстояния intercharacter, чтобы позиционировать символ ^. Если выходной массив lpGlyphs использован на вызове на ExtTextOut, флаг ETO_GLYPH_INDEX должен быть установлен.

GetCharacterPlacement ПРОВЕРЯЕТ lpOrder, lpDx, lpCaretPos, lpOutString, и участники lpGlyphs структуры GCP_RESULTS и заполняет соответствовать подготавливается если эти участники не установлены на НЕДЕЙСТВИТЕЛЬНЫЙ. Если GetCharacterPlacement не может заполнить массив, это устанавливает соответствующий элемент на НЕДЕЙСТВИТЕЛЬНЫЙ. Чтобы гарантировать поиск правильной информации, приложение ответственное за установку элемента в правильный адрес перед вызовом функции и для проверки величины элемента после вызова. Если GCP_JUSTIFY или величины GCP_USEKERNING даны, lpDx и/или участники lpCaretPos должны иметь правильные адресы. Также, элемент lpDx должен иметь правильный адрес если GCP_JUSTIFYIN дан.

При обработке оправдания, если конечные символы в строке - пробелы, функция уменьшает длину строки и удаляет пробелы до обработки оправдания. Если массив состоит из только пробелов, функция возвращает ошибку.

Смотри Также

ExtTextOut, GCP_RESULTS, GetCharABCWidths, GetCharWidth32, GetFontLanguageInfo, GetStringTypeEx, GetTextExtentPoint32, GetTextMetrics


Вверх Version 1.3, Oct 26 2010 © 2007, 2010, mrhx Вверх
 mrhx software  Русский перевод OpenGL  Русский перевод Win32 API
 
Используются технологии uCoz