我试图在不使用 GDI api 的情况下计算直接写入中 unicode 字符的宽度。我的问题是一些字符是全角字符,有些是半角字符,因此下面的公式不起作用,因为左侧轴承和右侧轴承因差异字符而异. 我该如何解决这个问题?
const size_t cSize = strlen((const char *)&globals->def_font.name[1]) + 1;
wchar_t* fontFamily = new wchar_t[cSize];
mbstowcs(fontFamily, (const char *)&globals->def_font.name[1], cSize);
const size_t size = strlen((const char *)data) + 1;
wchar_t* textData = new wchar_t[size];
mbstowcs(textData, (const char *)data, size);
IDWriteFontFace* fontName = GetFontFaceName(fontFamily);
IDWriteFontFace1* fontName1 = static_cast <IDWriteFontFace1*> (fontName);
//UINT32 textLength = fontName1->GetGlyphCount();
UINT32 textLength = (UINT32)wcslen(textData);
UINT32* pCodePoints = new UINT32[textLength];
ZeroMemory(pCodePoints, sizeof(UINT32)* textLength);
UINT16* pGlyphIndices = new UINT16[textLength];
ZeroMemory(pGlyphIndices, sizeof(UINT16)* textLength);
for (unsigned int i = 0; i < textLength; ++i)
{
pCodePoints[i] = textData[i];
}
// Get text length
HRESULT hr = fontName1->GetGlyphIndices(
pCodePoints,
textLength,
pGlyphIndices
);
if (FAILED(hr))
{
MessageBox(NULL, L"Get glyph indices failed!", L"Error", 0);
return 1;
}
// Create path geometry
hr = direct2DFactory->CreatePathGeometry(&pathGeometry);
if (FAILED(hr))
{
MessageBox(NULL, L"Create path geometry failed!", L"Error", 0);
return 1;
}
// Open sink
hr = pathGeometry->Open(&pGeometrySink);
if (FAILED(hr))
{
MessageBox(NULL, L"Open geometry sink failed!", L"Error", 0);
return 1;
}
float fontSize_ = textFormat->GetFontSize();
// Get glyph run outline
hr = fontName->GetGlyphRunOutline(
fontSize_, // font size
pGlyphIndices,
NULL,
NULL,
textLength,
FALSE,
FALSE,
pGeometrySink
);
if (FAILED(hr))
{
MessageBox(NULL, L"Get glyph run outline failed!", L"Error", 0);
return 1;
}
D2D1_MATRIX_3X2_F matrix_;
hdc->GetTransform(&matrix_);
direct2DFactory->CreateTransformedGeometry(
pathGeometry,
matrix_,
&pTransformedGeometry
);
// Close sink
D2D1_RECT_F rect;
pTransformedGeometry->GetBounds(matrix_, &rect);
pGeometrySink->Close();
DWRITE_GLYPH_METRICS* glyphmetrics = new DWRITE_GLYPH_METRICS[textLength];
fontName1->GetDesignGlyphMetrics(pGlyphIndices, textLength, glyphmetrics);
fontName1->GetMetrics(&fontMetrics);
float boundingBox = fontMetrics.glyphBoxRight - fontMetrics.glyphBoxLeft;
//Actual point calculation
// fontSize = textFormat->GetFontSize();
float fontHeight = ((fontMetrics.ascent + fontMetrics.descent )* fontSize_) / (fontMetrics.designUnitsPerEm);
index = *data;
n_widths[index] = (((glyphmetrics->advanceWidth + glyphmetrics->leftSideBearing + glyphmetrics->rightSideBearing) * fontSize_) / (fontMetrics.designUnitsPerEm)) ;
n_widths[index] = n_widths[index]* 1.33;**
//Release the glyphmetrics
delete[]glyphmetrics;
//delete[]pCodePoints;
delete[]pGlyphIndices;
//delete[]fontFamily;
delete[]textData;
glyphmetrics = NULL;
textLayout->GetMetrics(&textMetrics);