共用方式為


如何列舉字型

此概觀會示範如何依系列名稱列舉系統字型集合中的字型。

此概觀包含下列部分:

步驟 1:取得系統字型集合。

使用 DirectWrite Factory 所提供的 GetSystemFontCollection 方法來傳回 IDWriteFontCollection 中所有的系統字型。

IDWriteFontCollection* pFontCollection = NULL;

// Get the system font collection.
if (SUCCEEDED(hr))
{
    hr = pDWriteFactory->GetSystemFontCollection(&pFontCollection);
}

步驟 2:取得字體系列計數。

接下來,使用 IDWriteFontCollection::GetFontFamilyCount,從字型集合取得字型系列計數。 我們將使用此方法來迴圈查看集合中的每個字型系列。

UINT32 familyCount = 0;

// Get the number of font families in the collection.
if (SUCCEEDED(hr))
{
    familyCount = pFontCollection->GetFontFamilyCount();
}

建立 For 迴圈。

for (UINT32 i = 0; i < familyCount; ++i)

現在您已擁有字型集合和字型計數,其餘步驟會循環處理每個字型系列,擷取 IDWriteFontFamily 物件並加以查詢。

步驟 3:取得字型系列。

透過使用 IDWriteFontCollection::GetFontFamily 並傳入當前索引 i,取得 IDWriteFontFamily 物件。

IDWriteFontFamily* pFontFamily = NULL;

// Get the font family.
if (SUCCEEDED(hr))
{
    hr = pFontCollection->GetFontFamily(i, &pFontFamily);
}

步驟 4:取得姓氏名稱。

使用 IDWriteFontFamily::GetFamilyNames取得字型系列名稱。 這是 IDWriteLocalizedStrings 物件。 它可以有多個本地化版本的字型家族名稱。

IDWriteLocalizedStrings* pFamilyNames = NULL;

// Get a list of localized strings for the family name.
if (SUCCEEDED(hr))
{
    hr = pFontFamily->GetFamilyNames(&pFamilyNames);
}

步驟 5:尋找區域名稱。

使用 IDWriteLocalizedStrings::FindLocaleName 方法,取得在您所需的語言環境中字型 family 名稱。 在此情況下,會先取得並請求預設語言環境。 如果無法運作,則會要求 「en-us」 地區設定。 如果找不到其中一個指定的地區設定,則此範例只會回復為索引 0,第一個可用的地區設定。

UINT32 index = 0;
BOOL exists = false;

wchar_t localeName[LOCALE_NAME_MAX_LENGTH];

if (SUCCEEDED(hr))
{
    // Get the default locale for this user.
    int defaultLocaleSuccess = GetUserDefaultLocaleName(localeName, LOCALE_NAME_MAX_LENGTH);

    // If the default locale is returned, find that locale name, otherwise use "en-us".
    if (defaultLocaleSuccess)
    {
        hr = pFamilyNames->FindLocaleName(localeName, &index, &exists);
    }
    if (SUCCEEDED(hr) && !exists) // if the above find did not find a match, retry with US English
    {
        hr = pFamilyNames->FindLocaleName(L"en-us", &index, &exists);
    }
}

// If the specified locale doesn't exist, select the first on the list.
if (!exists)
    index = 0;

步驟 6:取得 [系列名稱字串長度] 和 [字串] 的長度。

最後,使用 IDWriteLocalizedStrings::GetStringLength取得系列名稱字串串的長度。 使用此長度來配置足以保存名稱的字串,然後使用 IDWriteLocalizedStrings::GetString取得字型系列名稱。

UINT32 length = 0;

// Get the string length.
if (SUCCEEDED(hr))
{
    hr = pFamilyNames->GetStringLength(index, &length);
}

// Allocate a string big enough to hold the name.
wchar_t* name = new (std::nothrow) wchar_t[length+1];
if (name == NULL)
{
    hr = E_OUTOFMEMORY;
}

// Get the family name.
if (SUCCEEDED(hr))
{
    hr = pFamilyNames->GetString(index, name, length+1);
}

結論

一旦您在地區設定中具有系列名稱或名稱,就可以列出這些名稱供用戶選擇,或將其傳遞至 CreateTextFormat,以開始使用指定的字型系列格式化文字等等。

範例程序代碼

若要檢視此範例的完整原始程式碼,請參閱 字型列舉範例