使用DX11渲染文本

时间:2012-09-03 21:28:04

标签: c# text directx slimdx directx-11

我想弄清楚如何在SlimDX中在屏幕上绘制文字。

初步研究并不令人鼓舞。我发现的唯一具体例子是:

http://www.aaronblog.us/?p=36

我正在尝试将此移植到我的代码中,但它证明非常困难,并且我开始怀疑4小时后这是否是正确的方法。

基本上,做一些像在屏幕上写文字一样简单的事情似乎很难。亚伦的方法似乎是目前唯一实用的方法。没有其他比较点。

是否有其他人可以提供任何建议?

P.S。我怀疑我现在可以为字母创建单独的图像,并编写一个例程来将字符串转换为一系列精灵。尽管如此,这似乎有些疯狂。

2 个答案:

答案 0 :(得分:4)

渲染文本确实有点复杂。呈现常规文本的唯一方法是使用Direct2D / DirectWrite。这只在DirectX10中得到支持。因此,您必须创建DirectX 10设备,DirectWrite和Direct2D工厂。然后,您可以创建可供DirectX 10和11设备使用的共享纹理。

此纹理将包含渲染后的文本。 Aaron使用此纹理将其与全屏融合。因此,您可以使用DirectWrite绘制完整的字符串。从本质上讲,这就像绘制纹理四边形一样。

另一种方法是,正如您已经提到的那样,绘制一个精灵表并将字符串分成几个精灵。我假设,后一种方式有点快,但我还没有测试过。我在Sprite & Text engine中使用了这种方法。请参阅方法AssertDeviceCreateCharTable

答案 1 :(得分:3)

有一个很好的DirectWrite包装器叫http://fw1.codeplex.com/

它是用c ++编写的,但为它制作一个混合模式包装器非常简单(这就是我为我的c#项目所做的)。

这是一个简单的例子:

.h文件

#pragma once
#include "Lib/FW1FontWrapper.h"
using namespace System::Runtime::InteropServices;

public ref class DX11FontWrapper
{
public:
    DX11FontWrapper(SlimDX::Direct3D11::Device^ device);
    void Draw(System::String^ str,float size,int x,int y,int color);
private:
    SlimDX::Direct3D11::Device^ device;
    IFW1FontWrapper* pFontWrapper;
};

.cpp文件

#include "StdAfx.h"
#include "DX11FontWrapper.h"

DX11FontWrapper::DX11FontWrapper(SlimDX::Direct3D11::Device^ device)
{
    this->device = device;

    IFW1Factory *pFW1Factory;
    FW1CreateFactory(FW1_VERSION, &pFW1Factory);
    ID3D11Device* dev = (ID3D11Device*)device->ComPointer.ToPointer();

    IFW1FontWrapper* pw;

    pFW1Factory->CreateFontWrapper(dev, L"Arial", &pw); 
    pFW1Factory->Release();

    this->pFontWrapper = pw;
}

void DX11FontWrapper::Draw(System::String^ str,float size,int x,int y, int color)
{
    ID3D11DeviceContext* pImmediateContext = 
        (ID3D11DeviceContext*)this->device->ImmediateContext->ComPointer.ToPointer();

    void* txt = (void*)Marshal::StringToHGlobalUni(str);
    pFontWrapper->DrawString(pImmediateContext, (WCHAR*)txt, size, x, y, color, 0);
    Marshal::FreeHGlobal(System::IntPtr(txt));
}
相关问题