Direct2D:将文本转换为路径

时间:2015-02-14 20:40:33

标签: c++ direct2d directwrite

我是Direct2D和DirectWrite的新手,并且仍在研究这些API提供的可能性。对于潜在的图形应用程序,我想知道是否可以将文本渲染为路径,以便可以像在矢量图形编辑器中一样修改各个点。是否有可能直接在Direct2D和DirectWrite中执行此类操作,或者至少有方法可以检索必要的信息并构建一个手动类似于文本的路径对象?

1 个答案:

答案 0 :(得分:1)

您在评论中引用的文章是正确的。关键是IDWriteFontFace::GetGlyphRunOutline。可以找到更多关于用法的here。而样本代码中的CustomTextRenderer文章中描述的函数如下(丑陋):

//  Gets GlyphRun outlines via IDWriteFontFace::GetGlyphRunOutline
//  and then draws and fills them using Direct2D path geometries
IFACEMETHODIMP CustomTextRenderer::DrawGlyphRun(
    _In_opt_ void* clientDrawingContext,
    FLOAT baselineOriginX,
    FLOAT baselineOriginY,
    DWRITE_MEASURING_MODE measuringMode,
    _In_ DWRITE_GLYPH_RUN const* glyphRun,
    _In_ DWRITE_GLYPH_RUN_DESCRIPTION const* glyphRunDescription,
    IUnknown* clientDrawingEffect)
{
    HRESULT hr = S_OK;

    // Create the path geometry.
    Microsoft::WRL::ComPtr<ID2D1PathGeometry> pathGeometry;
    hr = D2DFactory->CreatePathGeometry(&pathGeometry);

    // Write to the path geometry using the geometry sink.
    Microsoft::WRL::ComPtr<ID2D1GeometrySink> sink;
    if (SUCCEEDED(hr))
    {
        hr = pathGeometry->Open(&sink);
    }

    // Get the glyph run outline geometries back from DirectWrite 
    // and place them within the geometry sink.
    if (SUCCEEDED(hr))
    {
        hr = glyphRun->fontFace->GetGlyphRunOutline(
            glyphRun->fontEmSize,
            glyphRun->glyphIndices,
            glyphRun->glyphAdvances,
            glyphRun->glyphOffsets,
            glyphRun->glyphCount,
            glyphRun->isSideways,
            glyphRun->bidiLevel % 2,
            sink.Get());
    }

    // Close the geometry sink
    if (SUCCEEDED(hr))
    {
        hr = sink.Get()->Close();
    }

    // Initialize a matrix to translate the origin of the glyph run.
    D2D1::Matrix3x2F const matrix = D2D1::Matrix3x2F(
        1.0f, 0.0f,
        0.0f, 1.0f,
        baselineOriginX, baselineOriginY);

    // Create the transformed geometry
    Microsoft::WRL::ComPtr<ID2D1TransformedGeometry> transformedGeometry;
    if (SUCCEEDED(hr))
    {
        hr = D2DFactory.Get()->CreateTransformedGeometry(
            pathGeometry.Get(),
            &matrix,
            &transformedGeometry);
    }

    // Draw the outline of the glyph run
    D2DDeviceContext->DrawGeometry(
        transformedGeometry.Get(),
        outlineBrush.Get());

    // Fill in the glyph run
    D2DDeviceContext->FillGeometry(
        transformedGeometry.Get(),
        fillBrush.Get());

    return hr;
}

在该示例中,在从文本创建路径几何体之后,它们只是移动到x和y参数中指定的位置,然后跟踪并填充几何体。由于逻辑原因,我将代码称为丑陋,特别是如果大纲调用失败,接收器可能无法关闭。但它只是示例代码。祝你好运。