public FontData GetFontData(string fontFamilyName, bool isItalic, bool isBold) { FontData data = new FontData() { IsValid = false, Bytes = null, FontFamilyName = fontFamilyName, IsItalic = isItalic, IsBold = isBold }; FontFamily fontFamily = new FontFamily(fontFamilyName); FontStyle fontStyle = isItalic ? FontStyles.Italic : FontStyles.Normal; FontWeight fontWeight = isBold ? FontWeights.Bold : FontWeights.Normal; Typeface typeface = new Typeface(fontFamily, fontStyle, fontWeight, FontStretches.Normal); GlyphTypeface glyphTypeface; if (typeface.TryGetGlyphTypeface(out glyphTypeface)) { using (var memoryStream = new MemoryStream()) { glyphTypeface.GetFontStream().CopyTo(memoryStream); data.Bytes = memoryStream.ToArray(); data.IsValid = true; } } return data; }
public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { var list = value as IReadOnlyCollection<FontFamily>; if (list == null) return DependencyProperty.UnsetValue; var returnList = new List<FontFamily>(); foreach (FontFamily font in list) { try { // Instantiate a TypeFace object with the font settings you want to use Typeface ltypFace = new Typeface(font, FontStyles.Normal, FontWeights.Normal, FontStretches.Normal); // Try to create a GlyphTypeface object from the TypeFace object GlyphTypeface lglyphTypeFace; if (ltypFace.TryGetGlyphTypeface(out lglyphTypeFace)) { returnList.Add(font); } } catch (Exception) {} } return returnList; }
internal Size MeasureText(string text, FontFamily fontFamily, FontStyle fontStyle, FontWeight fontWeight, FontStretch fontStretch, double fontSize) { var typeface = new Typeface(fontFamily, fontStyle, fontWeight, fontStretch); GlyphTypeface glyphTypeface; if (!typeface.TryGetGlyphTypeface(out glyphTypeface)) { return MeasureTextSize(text, fontFamily, fontStyle, fontWeight, fontStretch, fontSize); } double totalWidth = 0; double height = 0; foreach (var t in text) { var glyphIndex = glyphTypeface.CharacterToGlyphMap[t]; var width = glyphTypeface.AdvanceWidths[glyphIndex] * fontSize; var glyphHeight = glyphTypeface.AdvanceHeights[glyphIndex] * fontSize; if (glyphHeight > height) { height = glyphHeight; } totalWidth += width; } return new Size(totalWidth, height); }
public static ImageSource ToFontAwesomeIcon(this string text, Brush foreBrush, FontStyle fontStyle, FontWeight fontWeight, FontStretch fontStretch) { var fontFamily = new FontFamily("/GitWorkItems;component/Resources/#FontAwesome"); if (fontFamily != null && !String.IsNullOrEmpty(text)) { //premier essai, on charge la police directement Typeface typeface = new Typeface(fontFamily, fontStyle, fontWeight, fontStretch); GlyphTypeface glyphTypeface; if (!typeface.TryGetGlyphTypeface(out glyphTypeface)) { //si ça ne fonctionne pas (et pour le mode design dans certains cas) on ajoute l'uri pack://application typeface = new Typeface(new FontFamily(new Uri("pack://application:,,,"), fontFamily.Source), fontStyle, fontWeight, fontStretch); if (!typeface.TryGetGlyphTypeface(out glyphTypeface)) throw new InvalidOperationException("No glyphtypeface found"); } //détermination des indices/tailles des caractères dans la police ushort[] glyphIndexes = new ushort[text.Length]; double[] advanceWidths = new double[text.Length]; for (int n = 0; n < text.Length; n++) { ushort glyphIndex; try { glyphIndex = glyphTypeface.CharacterToGlyphMap[text[n]]; } catch (Exception) { glyphIndex = 42; } glyphIndexes[n] = glyphIndex; double width = glyphTypeface.AdvanceWidths[glyphIndex] * 1.0; advanceWidths[n] = width; } try { //création de l'objet DrawingImage (compatible avec Imagesource) à partir d'un glyphrun GlyphRun gr = new GlyphRun(glyphTypeface, 0, false, 1.0, glyphIndexes, new Point(0, 0), advanceWidths, null, null, null, null, null, null); GlyphRunDrawing glyphRunDrawing = new GlyphRunDrawing(foreBrush, gr); return new DrawingImage(glyphRunDrawing); } catch (Exception ex) { // ReSharper disable LocalizableElement Console.WriteLine("Error in generating Glyphrun : " + ex.Message); // ReSharper restore LocalizableElement } } return null; }
static EmojiCharacters() { var typeface = new System.Windows.Media.Typeface(EmojiFontName); _Emojis = new Dictionary <int, EmojiCharacter>(); if (typeface.TryGetGlyphTypeface(out _Typeface)) { using (var s = _Typeface.GetFontStream()) { var r = new Typography.OpenFont.OpenFontReader(); var m_openfont = r.Read(s, Typography.OpenFont.ReadFlags.Full); _UnitsPerEm = m_openfont.UnitsPerEm; var colrTable = m_openfont.COLRTable; int palette = 0; // FIXME: support multiple palettes? var brushs = new Dictionary <Color, Brush>(); byte R, G, B, A; foreach (var kv in _Typeface.CharacterToGlyphMap) { var glyphIndex = kv.Value; if (colrTable.LayerIndices.TryGetValue(glyphIndex, out var layer_index)) { int endIndex = layer_index + colrTable.LayerCounts[glyphIndex]; var layers = new EmojiGlyphLayer[endIndex - layer_index]; for (int i = layer_index; i < endIndex; ++i) { ushort sub_gid = colrTable.GlyphLayers[i]; int cid = m_openfont.CPALTable.Palettes[palette] + colrTable.GlyphPalettes[i]; m_openfont.CPALTable.GetColor(cid, out R, out G, out B, out A); var color = Color.FromArgb(A, R, G, B); if (!brushs.TryGetValue(color, out Brush brush)) { brush = new SolidColorBrush(color); brushs.Add(color, brush); } layers[i - layer_index] = new EmojiGlyphLayer() { Brush = brush, //Color = Color.FromArgb(A, R, G, B), LayerIndex = sub_gid }; } var glyph = m_openfont.Lookup(kv.Key); var width = glyph.OriginalAdvanceWidth; if (!glyph.HasOriginalAdvancedWidth) { width = m_openfont.GetHAdvanceWidthFromGlyphIndex(glyphIndex); } _Emojis.Add(kv.Key, new EmojiCharacter(layers, width, Char.ConvertFromUtf32(kv.Key).Length)); } } } } }
/// <summary> /// Create a WPF GlyphTypeface and retrieve font data from it. /// </summary> internal static XFontSource CreateFontSource(string familyName, FontResolvingOptions fontResolvingOptions, out WpfFontFamily wpfFontFamily, out WpfTypeface wpfTypeface, out WpfGlyphTypeface wpfGlyphTypeface, string typefaceKey) { if (string.IsNullOrEmpty(typefaceKey)) { typefaceKey = XGlyphTypeface.ComputeKey(familyName, fontResolvingOptions); } XFontStyle style = fontResolvingOptions.FontStyle; #if DEBUG if (StringComparer.OrdinalIgnoreCase.Compare(familyName, "Segoe UI Semilight") == 0 && (style & XFontStyle.BoldItalic) == XFontStyle.Italic) { familyName.GetType(); } #endif // Use WPF technique to create font data. wpfTypeface = XPrivateFontCollection.TryCreateTypeface(familyName, style, out wpfFontFamily); #if DEBUG__ if (wpfTypeface != null) { WpfGlyphTypeface glyphTypeface; ICollection <WpfTypeface> list = wpfFontFamily.GetTypefaces(); foreach (WpfTypeface tf in list) { if (!tf.TryGetGlyphTypeface(out glyphTypeface)) { Debug - Break.Break(); } } //if (!WpfTypeface.TryGetGlyphTypeface(out glyphTypeface)) // throw new InvalidOperationException(PSSR.CannotGetGlyphTypeface(familyName)); } #endif if (wpfFontFamily == null) { wpfFontFamily = new WpfFontFamily(familyName); } if (wpfTypeface == null) { wpfTypeface = FontHelper.CreateTypeface(wpfFontFamily, style); } // Let WPF choose the right glyph typeface. if (!wpfTypeface.TryGetGlyphTypeface(out wpfGlyphTypeface)) { throw new InvalidOperationException(PSSR.CannotGetGlyphTypeface(familyName)); } // Get or create the font source and cache it unter the specified typeface key. XFontSource fontSource = XFontSource.GetOrCreateFromWpf(typefaceKey, wpfGlyphTypeface); return(fontSource); }
public static XGlyphTypeface GetOrCreateFromWpf(WpfTypeface wpfTypeface) { #if DEBUG if (wpfTypeface.FontFamily.Source == "Segoe UI Semilight") { wpfTypeface.GetType(); } #endif //string typefaceKey = ComputeKey(wpfTypeface); //XGlyphTypeface glyphTypeface; //if (GlyphTypefaceCache.TryGetGlyphTypeface(typefaceKey, out glyphTypeface)) //{ // // We have the glyph typeface already in cache. // return glyphTypeface; //} // Lock around TryGetGlyphTypeface and AddGlyphTypeface. try { Lock.EnterFontFactory(); // Create WPF glyph typeface. WpfGlyphTypeface wpfGlyphTypeface; if (!wpfTypeface.TryGetGlyphTypeface(out wpfGlyphTypeface)) { return(null); } string typefaceKey = ComputeKey(wpfGlyphTypeface); string name1 = wpfGlyphTypeface.DesignerNames[FontHelper.CultureInfoEnUs]; string name2 = wpfGlyphTypeface.FaceNames[FontHelper.CultureInfoEnUs]; string name3 = wpfGlyphTypeface.FamilyNames[FontHelper.CultureInfoEnUs]; string name4 = wpfGlyphTypeface.ManufacturerNames[FontHelper.CultureInfoEnUs]; string name5 = wpfGlyphTypeface.Win32FaceNames[FontHelper.CultureInfoEnUs]; string name6 = wpfGlyphTypeface.Win32FamilyNames[FontHelper.CultureInfoEnUs]; XGlyphTypeface glyphTypeface; if (GlyphTypefaceCache.TryGetGlyphTypeface(typefaceKey, out glyphTypeface)) { // We have the glyph typeface already in cache. return(glyphTypeface); } XFontFamily fontFamily = XFontFamily.GetOrCreateFromWpf(wpfTypeface.FontFamily); XFontSource fontSource = XFontSource.GetOrCreateFromWpf(typefaceKey, wpfGlyphTypeface); glyphTypeface = new XGlyphTypeface(typefaceKey, fontFamily, fontSource, (XStyleSimulations)wpfGlyphTypeface.StyleSimulations, wpfTypeface, wpfGlyphTypeface); GlyphTypefaceCache.AddGlyphTypeface(glyphTypeface); return(glyphTypeface); } finally { Lock.ExitFontFactory(); } }
internal void GetShapeableText( Typeface typeface, CharacterBufferReference characterBufferReference, int stringLength, TextRunProperties textRunProperties, CultureInfo digitCulture, bool isRightToLeftParagraph, IList<TextShapeableSymbols> shapeableList, IShapeableTextCollector collector, TextFormattingMode textFormattingMode ) { if (!typeface.Symbol) { Lookup(typeface).GetShapeableText( characterBufferReference, stringLength, textRunProperties, digitCulture, isRightToLeftParagraph, shapeableList, collector, textFormattingMode ); } else { // It's a non-Unicode ("symbol") font, where code points have non-standard meanings. We // therefore want to bypass the usual itemization and font linking. Instead, just map // everything to the default script and first GlyphTypeface. ShapeTypeface shapeTypeface = new ShapeTypeface( typeface.TryGetGlyphTypeface(), null // device font ); collector.Add( shapeableList, new CharacterBufferRange(characterBufferReference, stringLength), textRunProperties, new MS.Internal.Text.TextInterface.ItemProps(), shapeTypeface, 1.0, // scale in Em false, // null shape textFormattingMode ); } }
private Media.GlyphTypeface LoadTypeface(string getFamily, int getFontSize, int getCellWidth, int getCellHeight) { Media.GlyphTypeface glyphTypeface; Media.FontFamily family = new Media.FontFamily(getFamily); Media.Typeface typeface = new Media.Typeface(family, FontStyles.Normal, FontWeights.Normal, FontStretches.Normal); typeface.TryGetGlyphTypeface(out glyphTypeface); fontSize = getFontSize; CellWidth = getCellWidth; CellHeight = getCellHeight; return(glyphTypeface); }
/// <summary> /// Init. /// </summary> public FontAdapter(Typeface font, double size) { _font = font; _size = size; _height = 96d / 72d * _size * _font.FontFamily.LineSpacing; _underlineOffset = 96d / 72d * _size * (_font.FontFamily.LineSpacing + font.UnderlinePosition); GlyphTypeface typeface; if (font.TryGetGlyphTypeface(out typeface)) { _glyphTypeface = typeface; } else { foreach (var sysTypeface in Fonts.SystemTypefaces) { if (sysTypeface.TryGetGlyphTypeface(out typeface)) break; } } }
public static GlyphRun Create(string text, Typeface typeface, double emSize, Point baselineOrigin = new Point()) { GlyphTypeface glyphTypeface; if (!typeface.TryGetGlyphTypeface(out glyphTypeface)) { throw new ArgumentException(string.Format("{0}: no GlyphTypeface found", typeface.FontFamily)); } var glyphIndices = new ushort[text.Length]; var advanceWidths = new double[text.Length]; for (int i = 0; i < text.Length; i++) { var glyphIndex = glyphTypeface.CharacterToGlyphMap[text[i]]; glyphIndices[i] = glyphIndex; advanceWidths[i] = glyphTypeface.AdvanceWidths[glyphIndex] * emSize; } return new GlyphRun(glyphTypeface, 0, false, emSize, glyphIndices, baselineOrigin, advanceWidths, null, null, null, null, null, null); }
private bool CheckGlyphRun() { if (glyphRun == null) { if (string.IsNullOrEmpty(Text)) { return false; } var typeface = new Typeface(FontFamily, FontStyle, FontWeight, FontStretch); GlyphTypeface glyphTypeface; if (!typeface.TryGetGlyphTypeface(out glyphTypeface)) { return false; } var glyphIndices = new ushort[Text.Length]; var advanceWidths = new double[Text.Length]; for (int i = 0; i < Text.Length; i++) { var glyphIndex = glyphTypeface.CharacterToGlyphMap[Text[i]]; glyphIndices[i] = glyphIndex; advanceWidths[i] = glyphTypeface.AdvanceWidths[glyphIndex] * FontSize; } glyphRun = new GlyphRun(glyphTypeface, 0, false, FontSize, glyphIndices, new Point(), advanceWidths, null, null, null, null, null, null); outline = glyphRun.BuildGeometry().GetWidenedPathGeometry(new Pen(null, OutlineThickness * 2d)); } return true; }
private void InitializeInternalState() { // Font text if (_glyphTypeface == null) { Typeface typeface = new Typeface(new FontFamily("Segoe UI"), FontStyles.Normal, FontWeights.Normal, FontStretches.Normal); if (!typeface.TryGetGlyphTypeface(out _glyphTypeface)) { throw new InvalidOperationException("No glyphtypeface found"); } } // Time bar display _timeBar = new TimeBar(TimeBarCanvas); //events this.Loaded += FASTBuildMonitorControl_Loaded; EventsScrollViewer.PreviewMouseWheel += MainWindow_MouseWheel; EventsScrollViewer.MouseWheel += MainWindow_MouseWheel; MouseWheel += MainWindow_MouseWheel; EventsCanvas.MouseWheel += MainWindow_MouseWheel; EventsScrollViewer.PreviewMouseLeftButtonDown += EventsScrollViewer_MouseDown; EventsScrollViewer.MouseDown += EventsScrollViewer_MouseDown; MouseDown += EventsScrollViewer_MouseDown; EventsCanvas.MouseDown += EventsScrollViewer_MouseDown; EventsScrollViewer.PreviewMouseLeftButtonUp += EventsScrollViewer_MouseUp; EventsScrollViewer.MouseUp += EventsScrollViewer_MouseUp; MouseUp += EventsScrollViewer_MouseUp; EventsCanvas.MouseUp += EventsScrollViewer_MouseUp; EventsScrollViewer.PreviewMouseDoubleClick += EventsScrollViewer_MouseDoubleClick; EventsScrollViewer.MouseDoubleClick += EventsScrollViewer_MouseDoubleClick; OutputTextBox.PreviewMouseDoubleClick += OutputTextBox_PreviewMouseDoubleClick; OutputTextBox.MouseDoubleClick += OutputTextBox_PreviewMouseDoubleClick; OutputTextBox.PreviewKeyDown += OutputTextBox_KeyDown; OutputTextBox.KeyDown += OutputTextBox_KeyDown; OutputTextBox.LayoutUpdated += OutputTextBox_LayoutUpdated; OutputWindowComboBox.SelectionChanged += OutputWindowComboBox_SelectionChanged; Dispatcher.BeginInvoke(DispatcherPriority.Loaded, new Action(() => { //update timer _timer = new DispatcherTimer(); _timer.Tick += HandleTick; _timer.Interval = new TimeSpan(TimeSpan.TicksPerMillisecond * 16); _timer.Start(); })); }
void InitializeDescriptiveTextTab() { var selectedTypeface = new Typeface( SelectedFontFamily, SelectedFontStyle, SelectedFontWeight, SelectedFontStretch ); GlyphTypeface glyphTypeface; if (selectedTypeface.TryGetGlyphTypeface(out glyphTypeface)) { // Create a table with two columns. var table = new Table(); table.CellSpacing = 5; var leftColumn = new TableColumn(); leftColumn.Width = new GridLength(2.0, GridUnitType.Star); table.Columns.Add(leftColumn); var rightColumn = new TableColumn(); rightColumn.Width = new GridLength(3.0, GridUnitType.Star); table.Columns.Add(rightColumn); var rowGroup = new TableRowGroup(); AddTableRow(rowGroup, "Family:", glyphTypeface.FamilyNames); AddTableRow(rowGroup, "Face:", glyphTypeface.FaceNames); AddTableRow(rowGroup, "Description:", glyphTypeface.Descriptions); AddTableRow(rowGroup, "Version:", glyphTypeface.VersionStrings); AddTableRow(rowGroup, "Copyright:", glyphTypeface.Copyrights); AddTableRow(rowGroup, "Trademark:", glyphTypeface.Trademarks); AddTableRow(rowGroup, "Manufacturer:", glyphTypeface.ManufacturerNames); AddTableRow(rowGroup, "Designer:", glyphTypeface.DesignerNames); AddTableRow(rowGroup, "Designer URL:", glyphTypeface.DesignerUrls); AddTableRow(rowGroup, "Vendor URL:", glyphTypeface.VendorUrls); AddTableRow(rowGroup, "Win32 Family:", glyphTypeface.Win32FamilyNames); AddTableRow(rowGroup, "Win32 Face:", glyphTypeface.Win32FaceNames); try { AddTableRow(rowGroup, "Font File URI:", glyphTypeface.FontUri.ToString()); } catch (System.Security.SecurityException) { // Font file URI is privileged information; just skip it if we don't have access. } table.RowGroups.Add(rowGroup); fontDescriptionBox.Document = new FlowDocument(table); fontLicenseBox.Text = NameDictionaryHelper.GetDisplayName(glyphTypeface.LicenseDescriptions); } else { fontDescriptionBox.Document = new FlowDocument(); fontLicenseBox.Text = String.Empty; } }
protected void CreateDrawTextList() { textDrawDict.Clear(); textDrawDict = null; textDrawDict = new Dictionary<ProgramViewItem, List<TextDrawItem>>(); Matrix m = PresentationSource.FromVisual(Application.Current.MainWindow).CompositionTarget.TransformToDevice; this.VisualTextRenderingMode = TextRenderingMode.ClearType; this.VisualTextHintingMode = TextHintingMode.Fixed; this.UseLayoutRounding = true; if (Items == null) { return; } if (Settings.Instance.MinimumHeight > 0) { // Items を表示順にソートする Items.Sort(Compare); // 前番組へのリンク ProgramViewItem wkPrev = null; String wkPrevDate = ""; foreach (ProgramViewItem info in Items) { if (wkPrev != null) { if (wkPrev.EventInfo.service_id != wkPrev.EventInfo.service_id) { // サービスIDが変わる => 局が変わる => その局の一番先頭の番組 wkPrev = null; } if (!wkPrevDate.Equals(info.EventInfo.start_time.AddHours(-4).ToShortDateString())) { // 1週間モード時、先頭は4時に切り替わる=4時間前に日付が変わるタイミング wkPrev = null; } } info.prevItem = wkPrev; wkPrev = info; wkPrevDate = info.EventInfo.start_time.AddHours(-4).ToShortDateString(); } double minimum = (Settings.Instance.FontSizeTitle + 2) * Settings.Instance.MinimumHeight; foreach (ProgramViewItem info in Items) { // 最低表示dot数よりも小さければ if (info.Height < minimum) { double wk1 = minimum - info.Height; // 調整幅(Total) double wk2 = 0; // 調整可能幅 double wk3 = wk1; // 調整後の要再調整幅 ProgramViewItem pr = info.prevItem; if (pr != null) { // 先頭ならやりようがない while (pr.Height < minimum + wk3) { // 調整できるだけの十分な高さが無い wk2 = pr.Height - minimum; // 無理にでも調整可能な幅を求める if (wk2 > 0) {} else { wk2 = 0; } // 念の為マイナスを排除 wk3 = wk3 - wk2; // 調整後の要再調整幅 if ( pr.prevTop == 0) { pr.prevTop = pr.TopPos; } pr.Height -= wk2; // 高さと if (pr.Height >= minimum) { pr.TopPos -= wk3; } // 開始位置の調整 pr = pr.prevItem; // 次(前) if (pr == null) { break; } // が無い?なら終わり } if (pr != null) { if ( pr.prevTop == 0) { pr.prevTop = pr.TopPos; } pr.Height -= wk3; // 高さと if (info.prevTop == 0) { info.prevTop = info.TopPos; } } info.TopPos -= wk1; // 開始位置の調整 info.Height = minimum; // 最低表示dot数 } else { info.TopPos -= wk1; // 先頭位置をずらす info.Height = minimum; // 最低表示dot数 } } } } Typeface typefaceNormal = null; Typeface typefaceTitle = null; GlyphTypeface glyphTypefaceNormal = null; GlyphTypeface glyphTypefaceTitle = null; try { if (Settings.Instance.FontName.Length > 0) { typefaceNormal = new Typeface(new FontFamily(Settings.Instance.FontName), FontStyles.Normal, FontWeights.Normal, FontStretches.Normal); } if (Settings.Instance.FontNameTitle.Length > 0) { if (Settings.Instance.FontBoldTitle == true) { typefaceTitle = new Typeface(new FontFamily(Settings.Instance.FontNameTitle), FontStyles.Normal, FontWeights.Bold, FontStretches.Normal); } else { typefaceTitle = new Typeface(new FontFamily(Settings.Instance.FontNameTitle), FontStyles.Normal, FontWeights.Normal, FontStretches.Normal); } } if (!typefaceNormal.TryGetGlyphTypeface(out glyphTypefaceNormal)) { typefaceNormal = null; } if (!typefaceTitle.TryGetGlyphTypeface(out glyphTypefaceTitle)) { typefaceTitle = null; } if (typefaceNormal == null) { typefaceNormal = new Typeface(new FontFamily("MS UI Gothic"), FontStyles.Normal, FontWeights.Normal, FontStretches.Normal); if (!typefaceNormal.TryGetGlyphTypeface(out glyphTypefaceNormal)) { MessageBox.Show("フォント指定が不正です"); return; } } if (typefaceTitle == null) { typefaceTitle = new Typeface(new FontFamily("MS UI Gothic"), FontStyles.Normal, FontWeights.Bold, FontStretches.Normal); if (!typefaceTitle.TryGetGlyphTypeface(out glyphTypefaceTitle)) { MessageBox.Show("フォント指定が不正です"); return; } } } catch (Exception ex) { MessageBox.Show(ex.Message + "\r\n" + ex.StackTrace); } try { double sizeNormal = Settings.Instance.FontSize; double sizeTitle = Settings.Instance.FontSizeTitle; foreach (ProgramViewItem info in Items) { List<TextDrawItem> textDrawList = new List<TextDrawItem>(); textDrawDict[info] = textDrawList; if (info.Height > 2) { if (info.Height < sizeTitle + 3) { //高さ足りない info.TitleDrawErr = true; } double totalHeight = -2; //分 string min; if (info.EventInfo.StartTimeFlag == 1) { min = info.EventInfo.start_time.Minute.ToString("d02") + " "; } else { min = "未定 "; } double useHeight = 0; if (RenderText(min, ref textDrawList, glyphTypefaceTitle, sizeTitle - 0.5, info.Width - 4, info.Height + 10, info.LeftPos - 1, info.TopPos - 1, ref useHeight, CommonManager.Instance.CustTitle1Color, m) == false) { info.TitleDrawErr = true; continue; } double widthOffset = sizeNormal * 1.7; //番組情報 if (info.EventInfo.ShortInfo != null) { //タイトル if (info.EventInfo.ShortInfo.event_name.Length > 0) { if (RenderText(info.EventInfo.ShortInfo.event_name, ref textDrawList, glyphTypefaceTitle, sizeTitle, info.Width - 6 - widthOffset, info.Height - 1 - totalHeight, info.LeftPos + widthOffset, info.TopPos + totalHeight, ref useHeight, CommonManager.Instance.CustTitle1Color, m) == false) { info.TitleDrawErr = true; continue; } totalHeight += Math.Floor(useHeight + (sizeNormal / 2)); } if (IsTitleIndent == false) { widthOffset = 0; } //説明 if (info.EventInfo.ShortInfo.text_char.Length > 0) { if (RenderText(info.EventInfo.ShortInfo.text_char, ref textDrawList, glyphTypefaceNormal, sizeNormal, info.Width - 10 - widthOffset, info.Height - 5 - totalHeight, info.LeftPos + widthOffset, info.TopPos + totalHeight, ref useHeight, CommonManager.Instance.CustTitle2Color, m) == false) { continue; } totalHeight += useHeight + sizeNormal; } //詳細 // if (info.EventInfo.ExtInfo != null) // { // if (info.EventInfo.ExtInfo.text_char.Length > 0) // { // if (RenderText(info.EventInfo.ExtInfo.text_char, ref textDrawList, glyphTypefaceNormal, sizeNormal, info.Width - 6 - widthOffset, info.Height - 6 - totalHeight, info.LeftPos + widthOffset, info.TopPos + totalHeight, ref useHeight, CommonManager.Instance.CustTitle2Color, m) == false) // { // continue; // } // totalHeight += useHeight; // } // } } } } } catch (Exception ex) { MessageBox.Show(ex.Message + "\r\n" + ex.StackTrace); } }
protected void CreateDrawTextList() { textDrawDict.Clear(); textDrawDict = null; textDrawDict = new Dictionary<ProgramViewItem, List<TextDrawItem>>(); Matrix m = PresentationSource.FromVisual(Application.Current.MainWindow).CompositionTarget.TransformToDevice; this.VisualTextRenderingMode = TextRenderingMode.ClearType; this.VisualTextHintingMode = TextHintingMode.Fixed; this.UseLayoutRounding = true; if (Items == null) { return; } Typeface typefaceNormal = null; Typeface typefaceTitle = null; GlyphTypeface glyphTypefaceNormal = null; GlyphTypeface glyphTypefaceTitle = null; try { if (Settings.Instance.FontName.Length > 0) { typefaceNormal = new Typeface(new FontFamily(Settings.Instance.FontName), FontStyles.Normal, FontWeights.Normal, FontStretches.Normal); } if (Settings.Instance.FontNameTitle.Length > 0) { if (Settings.Instance.FontBoldTitle == true) { typefaceTitle = new Typeface(new FontFamily(Settings.Instance.FontNameTitle), FontStyles.Normal, FontWeights.Bold, FontStretches.Normal); } else { typefaceTitle = new Typeface(new FontFamily(Settings.Instance.FontNameTitle), FontStyles.Normal, FontWeights.Normal, FontStretches.Normal); } } if (!typefaceNormal.TryGetGlyphTypeface(out glyphTypefaceNormal)) { typefaceNormal = null; } if (!typefaceTitle.TryGetGlyphTypeface(out glyphTypefaceTitle)) { typefaceTitle = null; } if (typefaceNormal == null) { typefaceNormal = new Typeface(new FontFamily("MS UI Gothic"), FontStyles.Normal, FontWeights.Normal, FontStretches.Normal); if (!typefaceNormal.TryGetGlyphTypeface(out glyphTypefaceNormal)) { MessageBox.Show("フォント指定が不正です"); return; } } if (typefaceTitle == null) { typefaceTitle = new Typeface(new FontFamily("MS UI Gothic"), FontStyles.Normal, FontWeights.Bold, FontStretches.Normal); if (!typefaceTitle.TryGetGlyphTypeface(out glyphTypefaceTitle)) { MessageBox.Show("フォント指定が不正です"); return; } } } catch (Exception ex) { MessageBox.Show(ex.Message + "\r\n" + ex.StackTrace); } try { double sizeNormal = Settings.Instance.FontSize; double sizeTitle = Settings.Instance.FontSizeTitle; foreach (ProgramViewItem info in Items) { List<TextDrawItem> textDrawList = new List<TextDrawItem>(); textDrawDict[info] = textDrawList; if (info.Height > 2) { if (info.Height < sizeTitle + 3) { //高さ足りない info.TitleDrawErr = true; } double totalHeight = -2; //分 string min; if (info.EventInfo.StartTimeFlag == 1) { min = info.EventInfo.start_time.Minute.ToString("d02") + " "; } else { min = "未定 "; } double useHeight = 0; if (RenderText(min, ref textDrawList, glyphTypefaceTitle, sizeTitle - 0.5, info.Width - 4, info.Height + 10, info.LeftPos - 1, info.TopPos - 1, ref useHeight, CommonManager.Instance.CustTitle1Color, m) == false) { info.TitleDrawErr = true; continue; } double widthOffset = sizeNormal * 1.7; //番組情報 if (info.EventInfo.ShortInfo != null) { //タイトル if (info.EventInfo.ShortInfo.event_name.Length > 0) { if (RenderText(info.EventInfo.ShortInfo.event_name, ref textDrawList, glyphTypefaceTitle, sizeTitle, info.Width - 6 - widthOffset, info.Height - 1 - totalHeight, info.LeftPos + widthOffset, info.TopPos + totalHeight, ref useHeight, CommonManager.Instance.CustTitle1Color, m) == false) { info.TitleDrawErr = true; continue; } totalHeight += Math.Floor(useHeight + (sizeNormal / 2)); } if (IsTitleIndent == false) { widthOffset = 0; } //説明 if (info.EventInfo.ShortInfo.text_char.Length > 0) { if (RenderText(info.EventInfo.ShortInfo.text_char, ref textDrawList, glyphTypefaceNormal, sizeNormal, info.Width - 10 - widthOffset, info.Height - 5 - totalHeight, info.LeftPos + widthOffset, info.TopPos + totalHeight, ref useHeight, CommonManager.Instance.CustTitle2Color, m) == false) { continue; } totalHeight += useHeight + sizeNormal; } //詳細 // if (info.EventInfo.ExtInfo != null) // { // if (info.EventInfo.ExtInfo.text_char.Length > 0) // { // if (RenderText(info.EventInfo.ExtInfo.text_char, ref textDrawList, glyphTypefaceNormal, sizeNormal, info.Width - 6 - widthOffset, info.Height - 6 - totalHeight, info.LeftPos + widthOffset, info.TopPos + totalHeight, ref useHeight, CommonManager.Instance.CustTitle2Color, m) == false) // { // continue; // } // totalHeight += useHeight; // } // } } } } } catch (Exception ex) { MessageBox.Show(ex.Message + "\r\n" + ex.StackTrace); } }
bool TrySetFontFamily(TextBlock block, string familyName) { var family = new FontFamily(familyName); var typeFace = new Typeface(family, FontStyles.Normal, FontWeights.Normal, FontStretches.Normal); GlyphTypeface glyphTypeFace; return typeFace.TryGetGlyphTypeface(out glyphTypeFace); }
public static bool FontExists(string fontname) { #if false // Get the glyphTypeface to see if the font exists. GlyphTypeface glyphTypeface; Typeface typeface = new Typeface(fontname); return typeface.TryGetGlyphTypeface(out glyphTypeface); #else // Doesn't seem to be an easy way to determine if a font exists. try { FontFamily family = new FontFamily(fontname); family.Dispose(); return true; } catch { return false; } #endif }
public static GlyphRun BuildGlyphRun(string text) { double fontSize = 50; GlyphRun glyphs = null; Typeface font = new Typeface("Arial"); GlyphTypeface glyphFace; if (font.TryGetGlyphTypeface(out glyphFace)) { glyphs = new GlyphRun(); System.ComponentModel.ISupportInitialize isi = glyphs; isi.BeginInit(); glyphs.GlyphTypeface = glyphFace; glyphs.FontRenderingEmSize = fontSize; char[] textChars = text.ToCharArray(); glyphs.Characters = textChars; ushort[] glyphIndices = new ushort[textChars.Length]; double[] advanceWidths = new double[textChars.Length]; for (int i = 0; i < textChars.Length; ++i) { int codepoint = textChars[i]; ushort glyphIndex = glyphFace.CharacterToGlyphMap[codepoint]; double glyphWidth = glyphFace.AdvanceWidths[glyphIndex]; glyphIndices[i] = glyphIndex; advanceWidths[i] = glyphWidth * fontSize; } glyphs.GlyphIndices = glyphIndices; glyphs.AdvanceWidths = advanceWidths; glyphs.BaselineOrigin = new Point(0, glyphFace.Baseline * fontSize); isi.EndInit(); } return glyphs; }
protected override void OnRender(DrawingContext dc) { dc.DrawRectangle(Background, null, new Rect(RenderSize)); this.VisualTextRenderingMode = TextRenderingMode.ClearType; this.VisualTextHintingMode = TextHintingMode.Fixed; if (Items == null) { return; } Typeface typefaceNormal = null; Typeface typefaceTitle = null; GlyphTypeface glyphTypefaceNormal = null; GlyphTypeface glyphTypefaceTitle = null; try { if (Settings.Instance.FontName.Length > 0) { typefaceNormal = new Typeface(new FontFamily(Settings.Instance.FontName), FontStyles.Normal, FontWeights.Normal, FontStretches.Normal); } if (Settings.Instance.FontNameTitle.Length > 0) { if (Settings.Instance.FontBoldTitle == true) { typefaceTitle = new Typeface(new FontFamily(Settings.Instance.FontNameTitle), FontStyles.Normal, FontWeights.Bold, FontStretches.Normal); } else { typefaceTitle = new Typeface(new FontFamily(Settings.Instance.FontNameTitle), FontStyles.Normal, FontWeights.Normal, FontStretches.Normal); } } if (!typefaceNormal.TryGetGlyphTypeface(out glyphTypefaceNormal)) { typefaceNormal = null; } if (!typefaceTitle.TryGetGlyphTypeface(out glyphTypefaceTitle)) { typefaceTitle = null; } if (typefaceNormal == null) { typefaceNormal = new Typeface(new FontFamily("MS UI Gothic"), FontStyles.Normal, FontWeights.Normal, FontStretches.Normal); if (!typefaceNormal.TryGetGlyphTypeface(out glyphTypefaceNormal)) { MessageBox.Show("フォント指定が不正です"); return; } } if (typefaceTitle == null) { typefaceTitle = new Typeface(new FontFamily("MS UI Gothic"), FontStyles.Normal, FontWeights.Bold, FontStretches.Normal); if (!typefaceTitle.TryGetGlyphTypeface(out glyphTypefaceTitle)) { MessageBox.Show("フォント指定が不正です"); return; } } } catch (Exception ex) { MessageBox.Show(ex.Message + "\r\n" + ex.StackTrace); } try { double sizeNormal = Settings.Instance.FontSize; double sizeTitle = Settings.Instance.FontSizeTitle; foreach (ReserveViewItem info in Items) { // ビットマップフォントがかすれる問題 double dInfoTopPos = Math.Floor(info.TopPos); double dInfoHeight = Math.Floor(info.Height); dc.DrawRectangle(Brushes.LightGray, null, new Rect(info.LeftPos, dInfoTopPos, info.Width, dInfoHeight)); if (dInfoHeight > 2) { SolidColorBrush color = Brushes.White; if (info.ReserveInfo.OverlapMode == 1) { color = Brushes.Yellow; //color = CommonManager.Instance.CustContentColorList[0x14]; } dc.DrawRectangle(color, null, new Rect(info.LeftPos + 1, dInfoTopPos + 1, info.Width - 2, dInfoHeight - 2)); if (dInfoHeight < 4 + sizeTitle + 2) { //高さ足りない info.TitleDrawErr = true; continue; } double totalHeight = 0; //分 string min; min = info.ReserveInfo.StartTime.Minute.ToString("d02") + " "; double useHeight = 0; if (RenderText(min, dc, glyphTypefaceNormal, sizeNormal, info.Width - 4, dInfoHeight - 4, info.LeftPos, dInfoTopPos, ref useHeight) == false) { info.TitleDrawErr = true; continue; } double widthOffset = sizeNormal * 2; //サービス名 if (info.ReserveInfo.StationName.Length > 0) { String serviceName = info.ReserveInfo.StationName; if (0x7880 <= info.ReserveInfo.OriginalNetworkID && info.ReserveInfo.OriginalNetworkID <= 0x7FE8) { serviceName += " (地デジ)"; } else if (info.ReserveInfo.OriginalNetworkID == 0x0004) { serviceName += " (BS)"; } else if (info.ReserveInfo.OriginalNetworkID == 0x0006) { serviceName += " (CS1)"; } else if (info.ReserveInfo.OriginalNetworkID == 0x0007) { serviceName += " (CS2)"; } else { serviceName += " (その他)"; } if (RenderText(serviceName, dc, glyphTypefaceTitle, sizeTitle, info.Width - 6 - widthOffset, dInfoHeight - 6 - totalHeight, info.LeftPos + widthOffset, dInfoTopPos + totalHeight, ref useHeight) == false) { info.TitleDrawErr = true; continue; } // ビットマップフォントがかすれる問題 totalHeight += useHeight + Math.Floor(sizeNormal / 2); } widthOffset = 2; //番組名 if (info.ReserveInfo.Title.Length > 0) { if (RenderText(info.ReserveInfo.Title, dc, glyphTypefaceNormal, sizeNormal, info.Width - 6 - widthOffset, dInfoHeight - 6 - totalHeight, info.LeftPos + widthOffset, dInfoTopPos + totalHeight, ref useHeight) == false) { info.TitleDrawErr = true; continue; } totalHeight += useHeight + sizeNormal; } } } } catch (Exception ex) { MessageBox.Show(ex.Message + "\r\n" + ex.StackTrace); } }
/// <summary> /// Calculates the concrete width for an abstract width value based on font metrics /// </summary> /// <param name="element">The element.</param> /// <param name="width">The abstract width.</param> /// <returns>Concrete width</returns> private static double GetAbstractWidth(DependencyObject element, double width) { if (element == null) return double.NaN; var fontFamily = TextBlock.GetFontFamily(element); var fontSize = TextBlock.GetFontSize(element); var face = new Typeface(fontFamily, FontStyles.Normal, FontWeights.Normal, FontStretches.Normal); GlyphTypeface glyph; if (face.TryGetGlyphTypeface(out glyph)) { var map = glyph.CharacterToGlyphMap['N']; var glyphWidth = glyph.AdvanceWidths[map]; var singleWidth = fontSize * glyphWidth; return Math.Round(width * singleWidth); } return double.NaN; }
/// <summary> /// Gets the font families. /// </summary> /// <returns> /// List of font families. /// </returns> private static IEnumerable<FontFamily> GetFontFamilies() { if (cachedFontFamilies == null) { var list = new List<FontFamily>(); foreach (var fontFamily in Fonts.SystemFontFamilies) { // Instantiate a TypeFace object with the font settings you want to use var ltypFace = new Typeface(fontFamily, FontStyles.Normal, FontWeights.Normal, FontStretches.Normal); try { GlyphTypeface gtf; if (ltypFace.TryGetGlyphTypeface(out gtf)) { list.Add(fontFamily); } } catch (FileFormatException) { Debug.WriteLine(fontFamily + " failed."); } } cachedFontFamilies = list.OrderBy(f => f.ToString()).ToArray(); } return cachedFontFamilies; }
public static GlyphRun CreateGlyphRun(string text, double size, Point position) { if (_glyphTypeface == null) { Typeface typeface = new Typeface("Arial"); if (!typeface.TryGetGlyphTypeface(out _glyphTypeface)) throw new InvalidOperationException("No glyphtypeface found"); } ushort[] glyphIndexes = new ushort[text.Length]; double[] advanceWidths = new double[text.Length]; var totalWidth = 0d; double glyphWidth; for (int n = 0; n < text.Length; n++) { ushort glyphIndex = (ushort)(text[n] - 29); glyphIndexes[n] = glyphIndex; if (!_glyphWidths.TryGetValue(glyphIndex, out glyphWidth)) { glyphWidth = _glyphTypeface.AdvanceWidths[glyphIndex] * size; _glyphWidths.Add(glyphIndex, glyphWidth); } advanceWidths[n] = glyphWidth; totalWidth += glyphWidth; } var offsetPosition = new Point(position.X - (totalWidth / 2), position.Y - 10 - size); GlyphRun glyphRun = new GlyphRun(_glyphTypeface, 0, false, size, glyphIndexes, offsetPosition, advanceWidths, null, null, null, null, null, null); return glyphRun; }
private static ImageSource GetImage(sd.FontFamily fontFamily) { const double height = 1; const double width = 2; const double fontSize = 1; var drawingGroup = new DrawingGroup(); var outerGeometry = new RectangleGeometry(new Rect(0, 0, width, height)); var geometryDrawing = new GeometryDrawing() { Geometry = outerGeometry }; geometryDrawing.Pen = new Pen(Brushes.Transparent, 0); drawingGroup.Children.Add(geometryDrawing); Typeface typeface = new Typeface(fontFamily.Name); GlyphTypeface glyphTypeFace; if (!typeface.TryGetGlyphTypeface(out glyphTypeFace)) glyphTypeFace = null; if (null != glyphTypeFace) { var glyphRun = new GlyphRun(); ((System.ComponentModel.ISupportInitialize)glyphRun).BeginInit(); glyphRun.GlyphTypeface = glyphTypeFace; glyphRun.FontRenderingEmSize = fontSize; var textChars = GetDisplayText(glyphTypeFace); glyphRun.Characters = textChars; ushort[] glyphIndices = new ushort[textChars.Length]; double[] advanceWidths = new double[textChars.Length]; for (int i = 0; i < textChars.Length; ++i) { int codePoint = textChars[i]; ushort glyphIndex = glyphTypeFace.CharacterToGlyphMap[codePoint]; double glyphWidht = glyphTypeFace.AdvanceWidths[glyphIndex]; glyphIndices[i] = glyphIndex; advanceWidths[i] = glyphWidht * fontSize; } if (glyphIndices.Length > 0) { glyphRun.GlyphIndices = glyphIndices; glyphRun.AdvanceWidths = advanceWidths; glyphRun.BaselineOrigin = new Point(0, glyphTypeFace.Baseline * fontSize); ((System.ComponentModel.ISupportInitialize)glyphRun).EndInit(); var glyphRunDrawing = new GlyphRunDrawing(Brushes.Black, glyphRun); drawingGroup.Children.Add(glyphRunDrawing); } } drawingGroup.ClipGeometry = outerGeometry; DrawingImage geometryImage = new DrawingImage(drawingGroup); // Freeze the DrawingImage for performance benefits. geometryImage.Freeze(); return geometryImage; }
private static ImageSource CreateGlyph(string text, FontFamily fontFamily, FontStyle fontStyle, FontWeight fontWeight, FontStretch fontStretch, Brush foreBrush) { if (fontFamily != null && !string.IsNullOrEmpty(text)) { var typeface = new Typeface(fontFamily, fontStyle, fontWeight, fontStretch); GlyphTypeface glyphTypeface; if (!typeface.TryGetGlyphTypeface(out glyphTypeface)) { throw Log.ErrorAndCreateException<InvalidOperationException>("No glyph type face found"); } var glyphIndexes = new ushort[text.Length]; var advanceWidths = new double[text.Length]; for (var i = 0; i < text.Length; i++) { ushort glyphIndex; try { var key = text[i]; if (!glyphTypeface.CharacterToGlyphMap.TryGetValue(key, out glyphIndex)) { glyphIndex = 42; } } catch (Exception) { glyphIndex = 42; } glyphIndexes[i] = glyphIndex; var width = glyphTypeface.AdvanceWidths[glyphIndex] * 1.0; advanceWidths[i] = width; } try { var glyphRun = new GlyphRun(glyphTypeface, 0, false, RenderingEmSize, glyphIndexes, new Point(0, 0), advanceWidths, null, null, null, null, null, null); var glyphRunDrawing = new GlyphRunDrawing(foreBrush, glyphRun); //TextOptions.SetTextRenderingMode(glyphRunDrawing, TextRenderingMode.Aliased); var drawingImage = new DrawingImage(glyphRunDrawing); //TextOptions.SetTextRenderingMode(drawingImage, TextRenderingMode.Aliased); return drawingImage; } catch (Exception ex) { Log.Error(ex, "Error in generating Glyphrun"); } } return null; }
public static TextMetrics MeasureText(string text, string fontFamily, double size) { var typeface = new Typeface(new FontFamily(fontFamily), FontStyles.Normal, FontWeights.Normal, FontStretches.Normal); GlyphTypeface glyphTypeface; if (!typeface.TryGetGlyphTypeface(out glyphTypeface)) throw new InvalidOperationException("No glyphtypeface found"); var glyphIndexes = new ushort[text.Length]; var advanceWidths = new double[text.Length]; double totalWidth = 0; for (int n = 0; n < text.Length; n++) { char key = text[n]; if (glyphTypeface.CharacterToGlyphMap.ContainsKey(key)) //may cause incorrect width value! { ushort glyphIndex = glyphTypeface.CharacterToGlyphMap[key]; glyphIndexes[n] = glyphIndex; double width = glyphTypeface.AdvanceWidths[glyphIndex]*size; advanceWidths[n] = width; totalWidth += width; } } //todo: measure height return new TextMetrics((int) Math.Truncate(totalWidth), 0); }
/// <summary> /// Create a WPF GlyphTypeface and retrieve font data from it. /// </summary> internal static XFontSource CreateFontSource(string familyName, FontResolvingOptions fontResolvingOptions, out WpfFontFamily wpfFontFamily, out WpfTypeface wpfTypeface, out WpfGlyphTypeface wpfGlyphTypeface, string typefaceKey) { if (string.IsNullOrEmpty(typefaceKey)) typefaceKey = XGlyphTypeface.ComputeKey(familyName, fontResolvingOptions); XFontStyle style = fontResolvingOptions.FontStyle; #if DEBUG if (StringComparer.OrdinalIgnoreCase.Compare(familyName, "Segoe UI Semilight") == 0 && (style & XFontStyle.BoldItalic) == XFontStyle.Italic) familyName.GetType(); #endif // Use WPF technique to create font data. wpfTypeface = XPrivateFontCollection.TryCreateTypeface(familyName, style, out wpfFontFamily); #if DEBUG__ if (wpfTypeface != null) { WpfGlyphTypeface glyphTypeface; ICollection<WpfTypeface> list = wpfFontFamily.GetTypefaces(); foreach (WpfTypeface tf in list) { if (!tf.TryGetGlyphTypeface(out glyphTypeface)) Debug-Break.Break(); } //if (!WpfTypeface.TryGetGlyphTypeface(out glyphTypeface)) // throw new InvalidOperationException(PSSR.CannotGetGlyphTypeface(familyName)); } #endif if (wpfFontFamily == null) wpfFontFamily = new WpfFontFamily(familyName); if (wpfTypeface == null) wpfTypeface = FontHelper.CreateTypeface(wpfFontFamily, style); // Let WPF choose the right glyph typeface. if (!wpfTypeface.TryGetGlyphTypeface(out wpfGlyphTypeface)) throw new InvalidOperationException(PSSR.CannotGetGlyphTypeface(familyName)); // Get or create the font source and cache it unter the specified typeface key. XFontSource fontSource = XFontSource.GetOrCreateFromWpf(typefaceKey, wpfGlyphTypeface); return fontSource; }
/// <summary> /// Return true if the specified typeface name is the symbol font. /// </summary> private static bool IsSymbolFont(string typefaceName) { bool isSymbolFont = false; Typeface typeface = new Typeface(typefaceName); if (typeface != null) { GlyphTypeface glyphTypeface = typeface.TryGetGlyphTypeface(); if (glyphTypeface != null && glyphTypeface.Symbol) { isSymbolFont = true; } } return isSymbolFont; }
private void CalculateTextProperty() { double availableWidth = ActualWidth - Padding.Width(); double ellipsesWidth, totalWidth; double fontSize = FontSize; int i, lastSlashPos; string str = FilePath; if( string.IsNullOrEmpty( str ) ) { Text = null; IsTextClipped = false; return; } if( _glyphTypeface == null ) { Typeface typeface = new Typeface( FontFamily, FontStyle, FontWeight, FontStretch ); if( !typeface.TryGetGlyphTypeface( out _glyphTypeface ) ) { throw new InvalidOperationException( "Glyph typeface is not found!!" ); } } ellipsesWidth = _glyphTypeface.AdvanceWidths[ _glyphTypeface.CharacterToGlyphMap[ '.' ] ] * fontSize * 3; totalWidth = ellipsesWidth; if( availableWidth <= totalWidth ) str = string.Empty; lastSlashPos = str.LastIndexOf( '\\' ); if( lastSlashPos == -1 ) lastSlashPos = str.Length; totalWidth += ellipsesWidth; for( i = lastSlashPos; i < str.Length; i++ ) { if( !AddCharToTotalWidth( str[i], fontSize, availableWidth, ref totalWidth ) ) break; } if( i < str.Length ) { Text = "..." + str.Substring( lastSlashPos, i - lastSlashPos ) + "..."; IsTextClipped = true; } else { totalWidth -= ellipsesWidth; for( i = lastSlashPos - 1; i >= 0; i-- ) { if( !AddCharToTotalWidth( str[i], fontSize, availableWidth, ref totalWidth ) ) break; } if( i == -1 ) { Text = str; IsTextClipped = false; } else { Text = "..." + str.Substring( i + 1 ); IsTextClipped = true; } } }
private static bool TypefaceContainsCharacter(Typeface typeface, char characterToCheck) { ushort glyphIndex; int unicodeValue = Convert.ToUInt16(characterToCheck); GlyphTypeface glyph; typeface.TryGetGlyphTypeface(out glyph); if (glyph != null && glyph.CharacterToGlyphMap.TryGetValue(unicodeValue, out glyphIndex)) { return true; } return false; }
/// <summary> /// Measures the size of the specified text by a faster method (using GlyphTypefaces). /// </summary> /// <param name="text"> /// The text. /// </param> /// <param name="fontFamily"> /// The font family. /// </param> /// <param name="fontSize"> /// The font size. /// </param> /// <param name="fontWeight"> /// The font weight. /// </param> /// <returns> /// The size of the text. /// </returns> protected OxySize MeasureTextByGlyphTypeface(string text, string fontFamily, double fontSize, double fontWeight) { if (string.IsNullOrEmpty(text)) { return OxySize.Empty; } var typeface = new Typeface( new FontFamily(fontFamily), FontStyles.Normal, GetFontWeight(fontWeight), FontStretches.Normal); GlyphTypeface glyphTypeface; if (!typeface.TryGetGlyphTypeface(out glyphTypeface)) { throw new InvalidOperationException("No glyph typeface found"); } return MeasureTextSize(glyphTypeface, fontSize, text); }
// Create a Typeface, taking into account a nasty WPF bugs regarding Arial Narrow. private Typeface CreateTypeface(string fontName, bool bold, bool italic) { if (!Util.FontExists(fontName)) fontName = "Arial"; // Map non-existant fonts to "Arial". if (fontName == "Arial Narrow") { // Arial Narrow doesn't work right in WPF. We can work around by going directly to the font file. string fontfileName; if (!bold && !italic) fontfileName = "arialn.ttf"; else if (bold && !italic) fontfileName = "arialnb.ttf"; else if (!bold && italic) fontfileName = "arialni.ttf"; else fontfileName = "arialnbi.ttf"; // Get font folder StringBuilder fontPath = new StringBuilder(260); if (SHGetSpecialFolderPath(IntPtr.Zero, fontPath, CSIDL_FONTS, false)) { // Get path to font name. string fontfile = Path.Combine(fontPath.ToString(), fontfileName); UriBuilder fontfileUriBuilder = new UriBuilder(new Uri(fontfile)); fontfileUriBuilder.Fragment = "Arial"; Typeface typeface = new Typeface(new FontFamily(fontfileUriBuilder.Uri.ToString()), italic ? FontStyles.Italic : FontStyles.Normal, bold ? FontWeights.Bold : FontWeights.Normal, FontStretches.Condensed); GlyphTypeface gtf; if (typeface.TryGetGlyphTypeface(out gtf)) return typeface; // Make sure that the font file really exists, by getting the glyph typeface. } } return new Typeface(new FontFamily(fontName), italic ? FontStyles.Italic : FontStyles.Normal, bold ? FontWeights.Bold : FontWeights.Normal, FontStretches.Normal); }
public static bool StaticInitialize() { bool bSuccess = true; // Font text if (_glyphTypeface == null) { Typeface typeface = new Typeface(new FontFamily("Segoe UI"), FontStyles.Normal, FontWeights.Normal, FontStretches.Normal); if (!typeface.TryGetGlyphTypeface(out _glyphTypeface)) { bSuccess = false; throw new InvalidOperationException("No glyphtypeface found"); } } return bSuccess; }
public void Init(Ioctls ioctls, Core core, Runtime runtime) { ioctls.maFontGetCount = delegate() { int count = 0; MoSync.Util.RunActionOnMainThreadSync(() => count = System.Windows.Media.Fonts.SystemTypefaces.Count); return(count); }; ioctls.maFontGetName = delegate(int _index, int _buffer, int _bufferLen) { if (_index > ioctls.maFontGetCount()) { return(MoSync.Constants.RES_FONT_INDEX_OUT_OF_BOUNDS); } else { String fontName = ""; MoSync.Util.RunActionOnMainThreadSync(() => { int count = 0; System.Collections.Generic.IEnumerator <Typeface> en = System.Windows.Media.Fonts.SystemTypefaces.GetEnumerator(); while (count < _index) { en.MoveNext(); count++; } System.Windows.Media.Typeface currentTypeFace = en.Current; System.Windows.Media.GlyphTypeface currentGlyph; currentTypeFace.TryGetGlyphTypeface(out currentGlyph); fontName = currentGlyph.FontFileName; fontName = (fontName.Split('.'))[0]; }); if (fontName.Length > _bufferLen) { return(MoSync.Constants.RES_FONT_INSUFFICIENT_BUFFER); } core.GetDataMemory().WriteStringAtAddress(_buffer, fontName, _bufferLen); return(MoSync.Constants.RES_FONT_OK); } }; ioctls.maFontLoadWithName = delegate(int _postScriptName, int _size) { String fontName = core.GetDataMemory().ReadStringAtAddress(_postScriptName); Typeface typeface = null; GlyphTypeface glyphTypeface = null; MoSync.Util.RunActionOnMainThreadSync(() => { int count = Fonts.SystemTypefaces.Count; System.Collections.Generic.IEnumerator <Typeface> en = Fonts.SystemTypefaces.GetEnumerator(); while (count != 0) { typeface = en.Current; if (typeface.TryGetGlyphTypeface(out glyphTypeface)) { if (glyphTypeface.FontFileName.StartsWith(fontName)) { break; } } en.MoveNext(); count--; } }); if (glyphTypeface == null) { return(-2); } mFonts.Add(glyphTypeface); return(mFonts.Count - 1); }; ioctls.maFontLoadDefault = delegate(int _type, int _style, int _size) { //RES_FONT_NO_TYPE_STYLE_COMBINATION //RES_FONT_INVALID_SIZE switch (_type) { case MoSync.Constants.FONT_TYPE_MONOSPACE: break; case MoSync.Constants.FONT_TYPE_SERIF: break; case MoSync.Constants.FONT_TYPE_SANS_SERIF: break; default: return(MoSync.Constants.RES_FONT_NO_TYPE_STYLE_COMBINATION); } return(0); }; ioctls.maFontSetCurrent = delegate(int _font) { mCurrentFont = mFonts[_font]; mCurrentFontSource = new System.Windows.Documents.FontSource(mCurrentFont); return(0); }; }
/// <summary> /// Get the required height and width of the specified text. Uses Glyph's /// </summary> public static Size MeasureText(string text, FontFamily fontFamily, FontStyle fontStyle, FontWeight fontWeight, FontStretch fontStretch, double fontSize) { Typeface typeface = new Typeface(fontFamily, fontStyle, fontWeight, fontStretch); GlyphTypeface glyphTypeface; if (!typeface.TryGetGlyphTypeface(out glyphTypeface)) { return MeasureTextSize(text, fontFamily, fontStyle, fontWeight, fontStretch, fontSize); } double totalWidth = 0; double height = 0; for (int n = 0; n < text.Length; n++) { ushort glyphIndex = glyphTypeface.CharacterToGlyphMap[text[n]]; double width = glyphTypeface.AdvanceWidths[glyphIndex] * fontSize; double glyphHeight = glyphTypeface.AdvanceHeights[glyphIndex] * fontSize; if (glyphHeight > height) { height = glyphHeight; } totalWidth += width; } return new Size(totalWidth, height); }