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

本文关键字:文件 字体 SharpDX | 更新日期: 2023-09-27 18:22:01

我想为windows 8应用程序生成图像,我将使用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;
    }

这与安装的字体配合得很好。。。。我在assets文件夹中有字体,我想使用-我有大约604种自定义字体,我动态地选择了字体-我知道还有很多事情要从文件夹中加载文件。。。。帮助plz

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

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