使用 SharpDX 绘制 SVG 图形

Draw SVG graphic with SharpDX

我在 C# 中为 Direct2D 使用 SharpDX。

对于 SVG,我发现 SharpDX 支持它:https://github.com/sharpdx/SharpDX/pull/954/files#diff-ab708c02d6344a22d99b1c932b72cc12

如何渲染 SVG 图形?

比如我想画这条鲸鱼:https://www.flaticon.com/free-icon/whale_123995

如果您从 AdvancedTextRenderingApp 示例开始,只需修改渲染循环,使其看起来像这样:

RenderLoop.Run(mainForm, () =>
{
    renderTarget.BeginDraw();
    renderTarget.Clear(bgcolor);

    // get an ID2D1DeviceContext5 interface. It will fail here if Windows is not version 1704+
    using (var ctx = renderTarget.QueryInterface<DeviceContext5>())
    {
        // create WIC factory
        using (var imagingFactory = new ImagingFactory())
        {
            // load a file as a stream using WIC
            using (var file = File.OpenRead("whale.svg"))
            {
                using (var stream = new WICStream(imagingFactory, file))
                {
                    // create the SVG document
                    using (var doc = ctx.CreateSvgDocument(stream, new Size2F(mainForm.Width, mainForm.Height)))
                    {
                        // draw it on the device context
                        ctx.DrawSvgDocument(doc);
                    }
                }
            }
        }
    }

    try
    {
        renderTarget.EndDraw();
    }
    catch
    {
        CreateResources();
    }
});

结果如下:

注意1:需要SharpDX.Direct2D1预发布包(我的版本是4.1.0-ci217),否则关键的CreateSvcDocument会因为某些原因无法使用

注2:ID2D1DeviceContext5 (DeviceContext5 in SharpDX) requires Windows 10 Creators Update.