2015-01-30 1 views
0

Итак, я знаю, что существует несколько потоков для того, как сделать преобразование между вышеупомянутыми системами. И я знаю, что они не от 1 до 1. Тем не менее, я надеюсь, что есть способ заставить все работать.Преобразование System.Windows.Forms.Font в System.Windows.Media.FontFamily не работает для нерегулярных стилей

Шрифты, о которых идет речь, являются лишь примерами, так как я уверен, что у других есть такая же проблема, Segoe UI просто мой шрифт по умолчанию. Что не работает, когда я выбираю Segoe UI Semibold Italic или какой-либо другой промежуточный шрифт.

Вот мой код преобразования:

// Font family 
FontFamilyConverter ffc = new FontFamilyConverter(); 
TextContent.FontFamily = (System.Windows.Media.FontFamily) 
    ffc.ConvertFromString(fontDialog.Font.Name); 
// Font size 
TextContent.FontSize = fontDialog.Font.Size; 

// Bold? 
TextContent.FontWeight = (fontDialog.Font.Bold ? FontWeights.Bold : FontWeights.Normal); 

// Italic? 
TextContent.FontStyle = (fontDialog.Font.Italic ? FontStyles.Italic : FontStyles.Normal); 

// Underline and strikethrough? 
TextContent.TextDecorations = new TextDecorationCollection(); 
if (fontDialog.Font.Strikeout) { 
    TextContent.TextDecorations.Add(TextDecorations.Strikethrough); 
} 
if (fontDialog.Font.Underline) { 
    TextContent.TextDecorations.Add(TextDecorations.Underline); 
} 

// Color 
TextContent.Foreground = new SolidColorBrush(
    System.Windows.Media.Color.FromArgb(fontDialog.Color.A, 
             fontDialog.Color.R, 
             fontDialog.Color.G, 
             fontDialog.Color.B) 
             ); 

С помощью отладчика, я знаю, что свойство Курсив должным образом установлен, но шрифт не приходит через, как Semibold Italic это просто приходит через, как Semibold. Если (когда в отладчике) я меняю FontFamily на "Segoe UI Semibold Italic", тогда он работает.

Есть ли что-то, что мне не хватает, чтобы иметь возможность правильно найти все стили?

Спасибо.

Примечание: Я знаю, что размер не работает правильно. Просто не зафиксировал его еще

+0

вот аналогичный вопрос: http://stackoverflow.com/questions/1297772/how-can-i-convert-a-system-drawing-font-to-a-system-windows-media-fonts-or- typef – MethodMan

+0

@MethodMan, я видел это. Он не учитывает, когда фактическое имя должно быть изменено для элемента управления WPF, чтобы вытащить правильный шрифт. Я уже использую методы из этого потока уже в моем коде. – David

+0

Я понимаю, что вы говорите ... так работает с известными именами шрифтов в этой строке 'TextContent.FontFamily = (System.Windows.Media.FontFamily) ffc.ConvertFromString (fontDialog.Font.Name);' ...? – MethodMan

ответ

1

Вот что я закончил с:

После диалогового возвратов OK:

FontFamilyConverter ffc = new FontFamilyConverter(); 
TextContent.FontFamily = (System.Windows.Media.FontFamily) ffc.ConvertFromString(getFontName(fontDialog.Font)); 

вспомогательный метод:

private List<string> limitFontList(List<string> fontList, string word) { 
    // Create a new list 
    var newFontList = new List<string>(); 

    // Go through each element in the list 
    foreach (var fontFamily in fontList) { 
     // If the elment contains the word 
     if (fontFamily.ToLower().Contains(word.ToLower())) { 
      // Add it to the new list 
      newFontList.Add(fontFamily); 
     } 
    } 

    // Return the new list if anything was put in it, otherwise the original list. 
    return newFontList.Count > 0 ? newFontList : fontList; 
} 

getFontName:

private string getFontName(Font font) { 
    // Holds the font we want to return. This will be the original name if 
    // a better one cannot be found 
    string fontWanted = font.FontFamily.Name; 

    // Create a new Media.FontFamily 
    var family = new System.Windows.Media.FontFamily(fontWanted); 

    /// Get the base font name 
    string baseFont = ""; // Holds the name 
    /* FamilyNames.Values will holds the base name, but it's in a collection 
    ** and the easiest way to get it is to use a foreach. To the best of my 
    ** knowledge, there is only ever one value in Values. 
    ** E.g. If the font set is Segoe UI SemiBold Italc, gets Segoe UI. 
    */ 
    foreach(var baseF in family.FamilyNames.Values){ 
     baseFont = baseF; 
    } 

    // If the baseFont is what we were passed in, then just return 
    if(baseFont == fontWanted) { 
     return fontWanted; 
    } 

    // Get the typeface by extracting the basefont from the name. 
    // Trim removes any preceeeding spaces. 
    string fontTypeface = fontWanted.Substring(baseFont.Length).Trim(); 


    // Will hold all of the font names to be checked. 
    var fontNames = new List<string>(); 


    // Go through all of the available typefaces, and add them to the list 
    foreach (var typeface in family.FamilyTypefaces) { 
     foreach(var fn in typeface.AdjustedFaceNames) { 
      fontNames.Add(baseFont + " " + fn.Value); 
     } 
    } 

    // Limit the list to elements which contain the specified typeface 
    fontNames = limitFontList(fontNames, fontTypeface); 


    // If the font is bold, and the original name doesn't have bold in it (semibold?) 
    if(!baseFont.ToLower().Contains("bold") && font.Bold) { 
     fontNames = limitFontList(fontNames, "bold"); 
    } 
    // In a similar manner for italics 
    if (!baseFont.ToLower().Contains("italic") && font.Italic) { 
     fontNames = limitFontList(fontNames, "italic"); 
    } 

    // If we have only one result left 
    if(fontNames.Count == 1) { 
     return fontNames[0]; 
    } 

    // Otherwise, we can't accurately determine what the long name is, 
    // So hope whatever the short name is will work. 
    return fontWanted; 
} 
Смежные вопросы