首页 > 解决方案 > wxHtmlDCRenderer,如何正确计算宽度

问题描述

我用来wxHtmlDCRenderer在框架上输出渲染的 HTML 文本。html文本很简单:

<h4>Anderson-Darling Test</h4>
<p>p-value: 0.958<br>
A<sup>2</sup>: 0.13</p>

由于wxHtmlDCRenderer需要提前设置 Width 和 Height,我使用以下代码来计算渲染 HTML 文本的大小。

wxSize GetHTMLTextSize(wxWindow* window, const wxString& HTMLText, double PixelScaleFactor, double FontScaleFactor)
{
        wxClientDC dc(window);

        wxHtmlWinParser parser;
        parser.SetDC(&dc, PixelScaleFactor, FontScaleFactor);
        auto HTMLCell = (wxHtmlCell*)parser.Parse(HTMLText);

        int w = window->GetSize().GetWidth();
        HTMLCell->Layout(w);

        int MaxWidth = HTMLCell->GetMaxTotalWidth();
        int Width = HTMLCell->GetWidth();

        return wxSize(MaxWidth, HTMLCell->GetHeight());
}

HTML 代码在设备上下文上的实际呈现发生在以下代码中:

void CHTMLTextBox::RenderHTML(wxDC* dc)
{
    double ScaleFactor = m_ParentWindow->GetDPIScaleFactor();

    if (m_Size == wxSize())
        m_Size =sys::util::GetHTMLTextSize(m_ParentWindow, m_HTMLText, ScaleFactor, ScaleFactor);


    //wxHtmlDCRenderer might change the user scale of DC
    double OldUsrScale_X, OldUsrScale_Y;
    dc->GetUserScale(&OldUsrScale_X, &OldUsrScale_Y);

    wxHtmlDCRenderer htmlDC;
    htmlDC.SetDC(dc, ScaleFactor, ScaleFactor);
    htmlDC.SetSize(m_Size.GetWidth(), m_Size.GetHeight());
    htmlDC.SetHtmlText(m_HTMLText);

    htmlDC.Render(m_StartPoint.x, m_StartPoint.y);

    int totalHeight = htmlDC.GetTotalHeight();
    int totalWidth = htmlDC.GetTotalWidth();

    //not sure if the following two lines needed at all??
    htmlDC.SetSize(totalWidth, totalHeight);
    htmlDC.Render(m_StartPoint.x, m_StartPoint.y);

    m_Size = wxSize(totalWidth, totalHeight);

    //restore user scale back
    dc->SetUserScale(OldUsrScale_X, OldUsrScale_Y);
}

如下所示,它正确地呈现 HTML 文本本身。计算的高度是正确的,但是我遇到了如下图所示的宽度问题:

在此处输入图像描述

问题是宽度似乎计算不正确,因为第一句(以 h4 标记开头)不适合单行但似乎已损坏。

顺便说一句,我在 Windows 10(VS 2019)上使用 wxWidgets 3.1.4。

任何想法表示赞赏!

标签: c++wxwidgets

解决方案


推荐阅读