0
我如何計算WinRT中文本的寬度和高度。我試圖通過將我的文本放入TextBlock並設置屬性是fontsize,fontfamily等。這將計算高度和寬度。但我無法獲得表演。有更好的性能來計算寬度和高度的其他方法嗎?請提出任何想法?如何計算WinRT中文本的寬度和高度?
我如何計算WinRT中文本的寬度和高度。我試圖通過將我的文本放入TextBlock並設置屬性是fontsize,fontfamily等。這將計算高度和寬度。但我無法獲得表演。有更好的性能來計算寬度和高度的其他方法嗎?請提出任何想法?如何計算WinRT中文本的寬度和高度?
由於在WinRT中沒有GDI,GDI +和FormattedText類,所以似乎DirectX是唯一的出路。你可以使用IDWriteTextLayout界面來做到這一點。
Size TextMeasure::Measure(String^ text, String^ fontFamily, float fontSize, Size layoutSize) {
// Create DWrite Factory
IDWriteFactory *pDWriteFactory = NULL;
HRESULT hr = DWriteCreateFactory(
DWRITE_FACTORY_TYPE::DWRITE_FACTORY_TYPE_SHARED,
__uuidof(IDWriteFactory),
reinterpret_cast<IUnknown**>(&pDWriteFactory)
);
if (FAILED(hr)) {
throw ref new Exception(hr, "DWriteCreateFactory failed.");
}
// Create TextFormat
IDWriteTextFormat *pDWriteTextFormat = NULL;
hr = pDWriteFactory->CreateTextFormat(
fontFamily->Begin(),
NULL,
DWRITE_FONT_WEIGHT::DWRITE_FONT_WEIGHT_NORMAL,
DWRITE_FONT_STYLE::DWRITE_FONT_STYLE_NORMAL,
DWRITE_FONT_STRETCH::DWRITE_FONT_STRETCH_NORMAL,
fontSize,
L"en-US",
&pDWriteTextFormat);
if (FAILED(hr)) {
pDWriteFactory->Release();
throw ref new Exception(hr, "CreateTextFormat failed.");
}
// Create TextLayout
IDWriteTextLayout *pDWriteTextLayout = NULL;
hr = pDWriteFactory->CreateTextLayout(
text->Begin(),
text->Length(),
pDWriteTextFormat,
layoutSize.Width,
layoutSize.Height,
&pDWriteTextLayout);
if (FAILED(hr)) {
pDWriteTextFormat->Release();
pDWriteFactory->Release();
throw ref new Exception(hr, "CreateTextLayout failed.");
}
// Get Text Metrics
DWRITE_TEXT_METRICS textMetrics;
hr = pDWriteTextLayout->GetMetrics(&textMetrics);
// Release referances
pDWriteTextFormat->Release();
pDWriteTextLayout->Release();
pDWriteFactory->Release();
if (FAILED(hr)) {
throw ref new Exception(hr, "GetMetrics failed.");
}
return *ref new Size(textMetrics.width, textMetrics.height);
}
請注意,爲了在C#/ VB/JavaScript中使用代碼,您可以將代碼放在運行時組件中。
你是指屏幕上的字符的高度或什麼?你能澄清你的預期結果嗎? :) – CalebB 2015-03-31 14:05:50
是的,我需要計算整個字符的寬度和高度。 – 2015-03-31 14:18:17