如何使用SharpDX绘制文本?

时间:2015-10-27 19:19:15

标签: c# sharpdx

我正在互联网上试图找到允许我从常规字体(不是精灵字体)中绘制文本的代码,并且只找到了对我没有帮助的片段。

有人有完整的源文件,可以让我使用SharpDX和D3D11 / DirectWrite轻松绘制文本吗?我想制作一个透明的覆盖窗口,显示一些信息(如Fraps)。我发现了一个教程,但它使用了一个精灵字体,我希望它可以在大小和字体面上进行自定义。

这是我到目前为止所做的:

using System;
using SharpDX;
using SharpDX.Direct3D11;
using SharpDX.Windows;
using SharpDX.Direct2D1;
using SharpDX.DirectWrite;
using SharpDX.DXGI;

namespace SharpDXRenderer
{
    static class Program
    {

        [STAThread]
        static void Main()
        {
            SharpDX.DirectWrite.TextFormat directWriteTextFormat;
            SharpDX.DirectWrite.Factory directWriteFactory;
            SharpDX.Direct2D1.SolidColorBrush directWriteFontColor;
            SharpDX.Direct2D1.RenderTarget direct2DRenderTarget;
            Surface d2dSurface;

            RenderForm form = new RenderForm("Example");

            var desc = new SwapChainDescription()
            {
                BufferCount = 1,//buffer count
                ModeDescription = new ModeDescription(form.ClientSize.Width,     form.ClientSize.Height, new Rational(60, 1), Format.R8G8B8A8_UNorm),//sview
                IsWindowed = true,
                OutputHandle = form.Handle,
                SampleDescription = new SampleDescription(1, 0),
                SwapEffect = SwapEffect.Discard,
                Usage = Usage.RenderTargetOutput
            };



            var d2dFactory = new SharpDX.Direct2D1.Factory();
            d2dSurface = backBuffer.QueryInterface<Surface>();

            direct2DRenderTarget = new SharpDX.Direct2D1.RenderTarget(d2dFactory, d2dSurface, new     SharpDX.Direct2D1.RenderTargetProperties(new     SharpDX.Direct2D1.PixelFormat(Format.Unknown,     SharpDX.Direct2D1.AlphaMode.Premultiplied)));

            directWriteFactory = new SharpDX.DirectWrite.Factory();

            directWriteTextFormat = new SharpDX.DirectWrite.TextFormat(directWriteFactory, "Calibri", 12) {     TextAlignment = SharpDX.DirectWrite.TextAlignment.Leading, ParagraphAlignment =     SharpDX.DirectWrite.ParagraphAlignment.Near };

            directWriteFontColor = new SharpDX.Direct2D1.SolidColorBrush(direct2DRenderTarget, Color.White);
        }
    }
}

我知道我错过了一个SwapChain,一个设备,我认为一个纹理,但我不确定我是否需要更多的东西。 这个backBuffer是我所缺少的,但我不知道它是什么类型。

d2dSurface = backBuffer.QueryInterface<Surface>();

有关文字和基本形状绘图的任何帮助表示赞赏。

提前致谢。

1 个答案:

答案 0 :(得分:2)

我对SharpDx完全不熟悉,所以请大家多加一点,但是我使用SharpDX.Direct2D1.DeviceContext在我的应用程序中渲染文本。我的理解是,Direct2D使文本相对容易呈现。 (至少在2d)https://github.com/spazzarama/Direct3D-Rendering-Cookbook上有很多例子/细节(与同名的SharpDx书有关)

<asp:image ID="ImageLetterCopy"  style="max-width: 100%;max-height: 100%"   runat="server" />