如何使用SharpDX中的文件字体?

时间:2014-09-15 19:58:09

标签: c# windows-8 direct2d sharpdx

我想为Windows 8 app生成图像,我将使用SharpDX API

这是我感谢应对并粘贴的代码示例

private MemoryStream RenderStaticTextToBitmap()
    {
        var width = 400;
        var height = 100;
        var pixelFormat = WicPixelFormat.Format32bppBGR;

        var wicFactory = new ImagingFactory();
        var dddFactory = new SharpDX.Direct2D1.Factory();
        var dwFactory = new SharpDX.DirectWrite.Factory();

        var wicBitmap = new Bitmap(
            wicFactory,
            width,
            height,
            pixelFormat,
            BitmapCreateCacheOption.CacheOnLoad);

        var renderTargetProperties = new RenderTargetProperties(
            RenderTargetType.Default,
            new D2DPixelFormat(Format.Unknown, AlphaMode.Unknown),
            0,
            0,
            RenderTargetUsage.None,
            FeatureLevel.Level_DEFAULT);
        var renderTarget = new WicRenderTarget(
            dddFactory,
            wicBitmap,
            renderTargetProperties)
        {
            TextAntialiasMode = TextAntialiasMode.Cleartype
        };

        renderTarget.BeginDraw();

        var textFormat = new TextFormat(dwFactory, "Consolas", 48)
        {
            TextAlignment = SharpDX.DirectWrite.TextAlignment.Center,
            ParagraphAlignment = ParagraphAlignment.Center
        };
        var textBrush = new SharpDX.Direct2D1.SolidColorBrush(
            renderTarget,
            SharpDX.Colors.Blue);

        renderTarget.Clear(Colors.White);
        renderTarget.DrawText(
            "Hi, mom!",
            textFormat,
            new RectangleF(0, 0, width, height),
            textBrush);

        renderTarget.EndDraw();

        var ms = new MemoryStream();

        var stream = new WICStream(
            wicFactory,
            ms);

        var encoder = new PngBitmapEncoder(wicFactory);
        encoder.Initialize(stream);

        var frameEncoder = new BitmapFrameEncode(encoder);
        frameEncoder.Initialize();
        frameEncoder.SetSize(width, height);
        frameEncoder.PixelFormat = WicPixelFormat.FormatDontCare;
        frameEncoder.WriteSource(wicBitmap);
        frameEncoder.Commit();

        encoder.Commit();

        frameEncoder.Dispose();
        encoder.Dispose();
        stream.Dispose();

        ms.Position = 0;
        return ms;
    }

这与安装的字体工作方式很好....我有资产文件夹中的字体,我想使用-i有大约604自定义字体,我动态选择字体,我知道有加载文件从文件夹....帮助PLZ

1 个答案:

答案 0 :(得分:3)

不幸的是,afaik,DirectWrite中没有API可以轻松支持这一点。您需要开发自己的字体加载器和相关类。 SharpDX示例CustomFont正在从资源中加载字体,因此您可以将其调整为从其他位置加载。

相关问题