使用RAD Studio XE7编译器,我正在尝试使用DirectWrite和提供的VCL TDirect2Dcanvas绘制文本。
只要我使用属于Segoe家族的字体,文本图效果就很好。但是,DirectWrite似乎无法使用脚本字体之类的几个字体,而当我尝试使用它们时,请后备到另一个字体。
当我尝试使用GDI绘制完全相同的文本时,脚本字体会很好地使用。我不知道我在做什么错。有人可以向我解释如何使用DirectWrite字体这样的字体?
这是我当前用来绘制带有DirectWrite的文本的代码:
void __fastcall TMainForm::btDirectWriteClick(TObject *Sender)
{
const std::wstring text = L"Test 😀 😬 😁 😂 😃 😄 😅 😆";
HDC hDC = ::GetDC(Handle);
std::auto_ptr<TCanvas> pGDICanvas(new TCanvas());
pGDICanvas->Handle = hDC;
pGDICanvas->Brush->Color = clWhite;
pGDICanvas->Brush->Style = bsSolid;
pGDICanvas->FillRect(TRect(0, 0, ClientWidth, ClientHeight));
::D2D1_RECT_F textRect;
textRect.left = 10;
textRect.top = 10;
textRect.right = ClientWidth - 10;
textRect.bottom = ClientHeight - 10;
std::unique_ptr<TDirect2DCanvas> pCanvas(new TDirect2DCanvas(hDC, TRect(0, 0, ClientWidth, ClientHeight)));
// configure Direct2D font
pCanvas->Font->Size = 40;
//pCanvas->Font->Name = L"Segoe Script"; // this works...
pCanvas->Font->Name = L"Script"; // ... but this not!
pCanvas->Font->Orientation = 0;
pCanvas->Font->Pitch = System::Uitypes::TFontPitch::fpVariable;
pCanvas->Font->Style = TFontStyles();
// get DirectWrite text format object
_di_IDWriteTextFormat pFormat = pCanvas->Font->Handle;
// found it?
if (!pFormat)
return;
pCanvas->RenderTarget->SetTextAntialiasMode(D2D1_TEXT_ANTIALIAS_MODE_CLEARTYPE);
::D2D1_COLOR_F color;
color.r = 0.0f;
color.g = 0.0f;
color.b = 0.0f;
color.a = 1.0f;
::ID2D1SolidColorBrush* pBrush = NULL;
// create solid color brush, use pen color if rect is completely filled with outline
pCanvas->RenderTarget->CreateSolidColorBrush(color, &pBrush);
// found it?
if (!pBrush)
return;
// set horiz alignment
pFormat->SetTextAlignment(DWRITE_TEXT_ALIGNMENT_LEADING);
// set vert alignment
pFormat->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_NEAR);
// set reading direction
pFormat->SetReadingDirection(DWRITE_READING_DIRECTION_LEFT_TO_RIGHT);
// set word wrapping mode
pFormat->SetWordWrapping(DWRITE_WORD_WRAPPING_NO_WRAP);
IDWriteInlineObject* pInlineObject = NULL;
::DWRITE_TRIMMING trimming;
trimming.delimiter = 0;
trimming.delimiterCount = 0;
trimming.granularity = DWRITE_TRIMMING_GRANULARITY_NONE;
// set text trimming
pFormat->SetTrimming(&trimming, pInlineObject);
pCanvas->BeginDraw();
pCanvas->RenderTarget->DrawText(text.c_str(), text.length(), pFormat, textRect, pBrush);
pCanvas->EndDraw();
}
作为一个额外的问题,我也非常有兴趣在我的应用程序中使用诸如字体WAWSOWER 5(https://fontawesome.com/)之类的自定义字体。我如何使用它们用DirectWrite绘制文本?
如果您是指Windows 10中的字体称为"脚本标准",据我所知,它的文件是script.fon。这种类型的位图字体不支持DirectWrite,您可以通过列举系统字体集合来分辨,此字体不会在那里。
关于自定义字体,MSDN上有一个方法https://learn.microsoft.com/en-us/windows/desktop/directwrite/custom-font-font-collections。