如何计算WinRT中文本的宽度和高度?

时间:2015-03-31 14:01:26

标签: c# .net windows-runtime winrt-xaml

如何计算WinRT中文本的宽度和高度。我尝试将我的文本放入TextBlock并设置属性是fontsize,fontfamily等。这将计算高度和宽度。但我无法获得表现。是否有其他方法可以更好地计算宽度和高度?请提出任何建议?

1 个答案:

答案 0 :(得分:0)

由于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中使用代码,您可以将代码放在运行时组件中。