Exemple #1
0
        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);
        }
Exemple #2
0
        /// <summary>
        /// 计算文本显示宽、高
        /// </summary>
        public static MeasureSize MeasureText(string text,
                                              System.Windows.Media.FontFamily fontFamily,
                                              System.Windows.FontStyle fontStyle,
                                              System.Windows.FontWeight fontWeight,
                                              System.Windows.FontStretch fontStretch,
                                              double fontSize)
        {
            System.Windows.Media.Typeface      typeface = new System.Windows.Media.Typeface(fontFamily, fontStyle, fontWeight, fontStretch);
            System.Windows.Media.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 MeasureSize(totalWidth, height));
        }
Exemple #3
0
 public object SetStretch(object handle, FontStretch stretch)
 {
     var font = (FontData)handle;
     font = font.Clone ();
     font.Stretch = DataConverter.ToWpfFontStretch (stretch);
     return font;
 }
        public GraphicsText(
            string text,
            double left, 
            double top, 
            double right, 
            double bottom,
            Color objectColor,
            double textFontSize,
            string textFontFamilyName,
            FontStyle textFontStyle,
            FontWeight textFontWeight,
            FontStretch textFontStretch,
            double actualScale)
        {
            this.text = text;
            this.rectangleLeft = left;
            this.rectangleTop = top;
            this.rectangleRight = right;
            this.rectangleBottom = bottom;
            this.graphicsObjectColor = objectColor;
            this.textFontSize = textFontSize;
            this.textFontFamilyName = textFontFamilyName;
            this.textFontStyle = textFontStyle;
            this.textFontWeight = textFontWeight;
            this.textFontStretch = textFontStretch;
            this.graphicsActualScale = actualScale;

            graphicsLineWidth = 2;      // used for drawing bounding rectangle when selected

            //RefreshDrawng();
        }
Exemple #5
0
        // copied and adapted from presenter::GetLabelWidthAndHeight(...)
        private double TestHelper_GetLabelWidthAndHeight(string text)
        {
            var defaultFontFamily  = new System.Windows.Media.FontFamily();
            var defaultFontStyle   = new System.Windows.FontStyle();
            var defaultFontStretch = new System.Windows.FontStretch();
            var defaultFontSizeEm  = 12.0;

            var typeFace = new Typeface(defaultFontFamily,
                                        defaultFontStyle,
                                        System.Windows.FontWeights.Normal,
                                        defaultFontStretch);

            var formattedText = new FormattedText(
                text,
                System.Globalization.CultureInfo.CurrentUICulture,
                FlowDirection.LeftToRight,
                typeFace,
                defaultFontSizeEm,
                Brushes.Black);

            var Padding = 15;   // empirical
            var width   = formattedText.Width + Padding;

            return(width);
        }
 public WpfFontFamilyInfo(FontFamily family, FontWeight weight, 
     FontStyle style, FontStretch stretch)
 {
     _family  = family;
     _weight  = weight;
     _style   = style;
     _stretch = stretch;
 }
Exemple #7
0
 public FontHandler(swm.FontFamily family, double size, sw.FontStyle style, sw.FontWeight weight, sw.FontStretch stretch)
 {
     Family         = new FontFamily(new FontFamilyHandler(family));
     Size           = size;
     WpfFontStyle   = style;
     WpfFontStretch = stretch;
     WpfFontWeight  = weight;
 }
        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;
        }
Exemple #9
0
 public Font(FontFamily family, double size, FontStyle style, FontWeight weight, FontStretch stretch)
     : this()
 {
     this.Family = family;
     this.Size = size;
     this.Style = style;
     this.Weight = weight;
     this.Stretch = stretch;
 }
        public static Size GetScreenSize(this string text, FontFamily fontFamily, double fontSize, FontStyle fontStyle, FontWeight fontWeight, FontStretch fontStretch) {
            fontFamily = fontFamily ?? new TextBlock().FontFamily;
            fontSize = fontSize > 0 ? fontSize : new TextBlock().FontSize;

            var typeface = new Typeface(fontFamily, fontStyle, fontWeight, fontStretch);
            var ft = new FormattedText(text ?? string.Empty, CultureInfo.CurrentCulture, FlowDirection.LeftToRight, typeface, fontSize, Brushes.Black);

            return new Size(ft.Width, ft.Height);
        }
Exemple #11
0
 public override object Create(string fontName, double size, FontStyle style, FontWeight weight, FontStretch stretch)
 {
     size = GetPointsFromDeviceUnits (size);
     return new FontData (new FontFamily (fontName), size) {
         Style = style.ToWpfFontStyle (),
         Weight = weight.ToWpfFontWeight (),
         Stretch = stretch.ToWpfFontStretch ()
     };
 }
Exemple #12
0
		public FontInfo(FontFamily fam, double sz, FontStyle style, FontStretch strc, FontWeight weight, SolidColorBrush c)
		{
			this.Family = fam;
			this.Size = sz;
			this.Style = style;
			this.Stretch = strc;
			this.Weight = weight;
			this.BrushColor = c;
		}
Exemple #13
0
 public static Size MeasureText(string text, FontFamily fontFamily, FontStyle fontStyle, FontWeight fontWeight, FontStretch fontStretch, double fontSize)
 {
     FormattedText ft = new FormattedText(text,
                                          CultureInfo.CurrentCulture,
                                          FlowDirection.LeftToRight,
                                          new Typeface(fontFamily, fontStyle, fontWeight, fontStretch),
                                          fontSize,
                                          Brushes.Black);
     return new Size(ft.Width, ft.Height);
 }
Exemple #14
0
 public Font(FontFamily family, double size, FontStretch stretch, FontStyle style, FontWeight weight, Color foreground)
     : this()
 {
     this.Family = family;
     this.Size = size;
     this.Stretch = stretch;
     this.Style = style;
     this.Weight = weight;
     this.Foreground = foreground;
 }
Exemple #15
0
 public static void SetSvgFontStretch(this HtmlElement element, System.Windows.FontStretch fontStretch, SvgValueConverter converter)
 {
     if (fontStretch == System.Windows.FontStretch.Normal)
     {
         element.ClearHtmlStyleProperty("font-stretch");
     }
     else
     {
         element.SetSvgAttribute("font-stretch", converter.ToFontStretchString(fontStretch));
     }
 }
Exemple #16
0
        internal static IDictionary<XmlLanguage, string> ConstructFaceNamesByStyleWeightStretch(
            FontStyle style,
            FontWeight weight,
            FontStretch stretch)
        {
            string faceName = BuildFaceName(style, weight, stretch);

            // Default comparer calls CultureInfo.Equals, which works for our purposes.
            Dictionary<XmlLanguage, string> faceNames = new Dictionary<XmlLanguage, string>(1);
            faceNames.Add(XmlLanguage.GetLanguage("en-us"), faceName);
            return faceNames;
        }
Exemple #17
0
        private static string BuildFaceName(
            FontStyle fontStyle,
            FontWeight fontWeight,
            FontStretch fontStretch
            )
        {
            string parsedStyleName   = null;
            string parsedWeightName  = null;
            string parsedStretchName = null;
            string regularFaceName   = "Regular";
            if (fontWeight != FontWeights.Normal)
                parsedWeightName = ((IFormattable)fontWeight).ToString(null, CultureInfo.InvariantCulture);

            if (fontStretch != FontStretches.Normal)
                parsedStretchName = ((IFormattable)fontStretch).ToString(null, CultureInfo.InvariantCulture);

            if (fontStyle != FontStyles.Normal)
                parsedStyleName = ((IFormattable)fontStyle).ToString(null, CultureInfo.InvariantCulture);

            // Build correct face string.
            // Set the initial capacity to be able to hold the word "Regular".
            StringBuilder faceNameBuilder = new StringBuilder(7);

            if (parsedStretchName != null)
            {
                faceNameBuilder.Append(parsedStretchName);
            }

            if (parsedWeightName != null)
            {
                if (faceNameBuilder.Length > 0)
                {
                    faceNameBuilder.Append(" ");
                }
                faceNameBuilder.Append(parsedWeightName);
            }

            if (parsedStyleName != null)
            {
                if (faceNameBuilder.Length > 0)
                {
                    faceNameBuilder.Append(" ");
                }
                faceNameBuilder.Append(parsedStyleName);
            }

            if (faceNameBuilder.Length == 0)
            {
                faceNameBuilder.Append(regularFaceName);
            }

            return faceNameBuilder.ToString();
        }         
 internal MatchingStyle(
     FontStyle       style,
     FontWeight      weight,
     FontStretch     stretch
     )
 {
     _vector = new Vector(
         (stretch.ToOpenTypeStretch() - FontStretches.Normal.ToOpenTypeStretch()) * FontStretchScale,
         style.GetStyleForInternalConstruction() * FontStyleScale,
         (weight.ToOpenTypeWeight() - FontWeights.Normal.ToOpenTypeWeight()) / 100.0 * FontWeightScale
         );
 }
Exemple #19
0
        public static SW.FontStretch ToWpfFontStretch(FontStretch value)
        {
            if (value == FontStretch.UltraCondensed) return SW.FontStretches.UltraCondensed;
            if (value == FontStretch.ExtraCondensed) return SW.FontStretches.ExtraCondensed;
            if (value == FontStretch.Condensed) return SW.FontStretches.Condensed;
            if (value == FontStretch.SemiCondensed) return SW.FontStretches.SemiCondensed;
            if (value == FontStretch.SemiExpanded) return SW.FontStretches.SemiExpanded;
            if (value == FontStretch.Expanded) return SW.FontStretches.Expanded;
            if (value == FontStretch.ExtraExpanded) return SW.FontStretches.ExtraExpanded;
            if (value == FontStretch.UltraExpanded) return SW.FontStretches.UltraExpanded;

            return SW.FontStretches.Normal;
        }
Exemple #20
0
        private void AddFont(FontFamily fontFamily, FontStretch fontStretch, string text)
        {
            var stackPanel = new StackPanel();
            stackPanel.Margin = new Thickness(5);

            stackPanel.Children.Add(NewTextBlock(fontFamily, FontWeights.Normal, FontStretches.Normal, fontFamily.ToString()));

            foreach (var weight in _weights)
            {
                stackPanel.Children.Add(NewTextBlock(fontFamily, weight, fontStretch, weight + ": " + text));
            }

            FontList.Children.Add(stackPanel);
        }
Exemple #21
0
 /// <summary>
 /// Construct a typeface 
 /// </summary>
 /// <param name="fontFamily">Font family</param>
 /// <param name="style">Font style</param>
 /// <param name="weight">Boldness of font</param> 
 /// <param name="stretch">Width of characters</param>
 public Typeface( 
     FontFamily      fontFamily, 
     FontStyle       style,
     FontWeight      weight, 
     FontStretch     stretch
     )
     : this(
         fontFamily, 
         style,
         weight, 
         stretch, 
         FontFamily.FontFamilyGlobalUI
         ) 
 {}
Exemple #22
0
        private static TextBlock NewTextBlock(FontFamily fontFamily, FontWeight weight, FontStretch fontStretch, string text)
        {
            var textBlock = new TextBlock
            {
                HorizontalAlignment = HorizontalAlignment.Left,
                VerticalAlignment = VerticalAlignment.Top,
                FontSize = PointsToPixels(12),
                Text = text,
                FontWeight = weight,
                FontFamily = fontFamily,
                FontStretch = fontStretch
            };

            return textBlock;
        }
        /// <summary>
        /// Convert FontStretch to string for serialization
        /// </summary>
        public static string FontStretchToString(FontStretch value)
        {
            string result;

            try
            {
                result = (string)(new FontStretchConverter().ConvertToString(value));
            }
            catch (NotSupportedException)
            {
                result = "";
            }

            return result;
        }
Exemple #24
0
 /// <summary>
 /// 计算文本显示宽、高
 /// </summary>
 /// <param name="text">The text.</param>
 /// <param name="fontFamily">The font family.</param>
 /// <param name="fontStyle">The font style.</param>
 /// <param name="fontWeight">The font weight.</param>
 /// <param name="fontStretch">The font stretch.</param>
 /// <param name="fontSize">Size of the font.</param>
 /// <returns></returns>
 public static MeasureSize MeasureTextSize(
     string text,
     System.Windows.Media.FontFamily fontFamily,
     System.Windows.FontStyle fontStyle,
     System.Windows.FontWeight fontWeight,
     System.Windows.FontStretch fontStretch,
     double fontSize)
 {
     System.Windows.Media.FormattedText ft = new System.Windows.Media.FormattedText(text,
                                                                                    System.Globalization.CultureInfo.CurrentCulture,
                                                                                    System.Windows.FlowDirection.LeftToRight,
                                                                                    new System.Windows.Media.Typeface(fontFamily, fontStyle, fontWeight, fontStretch),
                                                                                    fontSize,
                                                                                    System.Windows.Media.Brushes.Black);
     return(new MeasureSize(ft.Width, ft.Height));
 }
        internal CachedTypeface(
            FontStyle        canonicalStyle,
            FontWeight       canonicalWeight,
            FontStretch      canonicalStretch,
            IFontFamily      firstFontFamily,
            ITypefaceMetrics typefaceMetrics,
            bool             nullFont
            )
        {
            _canonicalStyle   = canonicalStyle;
            _canonicalWeight  = canonicalWeight;
            _canonicalStretch = canonicalStretch;

            Invariant.Assert(firstFontFamily != null && typefaceMetrics != null);
            
            _firstFontFamily  = firstFontFamily;
            _typefaceMetrics  = typefaceMetrics;
            _nullFont         = nullFont;            
        }        
        /// <summary>
        /// Calculates the desired width for the given text.
        /// </summary>
        /// <param name="text">The text.</param>
        /// <param name="fontSize">The used fontsize.</param>
        /// <param name="fontFamily">The used font family.</param>
        /// <param name="fontWeight">The used font weight.</param>
        /// <param name="fontStyle">The used font style.</param>
        /// <param name="fontStretch">The used font stretch.</param>
        /// <param name="flowDirection">The used flow direction.</param>
        /// <param name="foreground">The used foreground brush.</param>
        /// <returns>A double representing the desired width for the given text.</returns>
        public static double CalculateWidth(this string text, double fontSize, FontFamily fontFamily, FontWeight fontWeight, FontStyle fontStyle, FontStretch fontStretch, FlowDirection flowDirection, Brush foreground)
        {
            var typeface = new Typeface(fontFamily, fontStyle, fontWeight, fontStretch);

            var formattedText = new FormattedText
                                    (
                                        text,
                                        CultureInfo.CurrentCulture,
                                        flowDirection,
                                        typeface,
                                        fontSize,
                                        foreground
                                    )
            {
                Trimming = TextTrimming.CharacterEllipsis
            };

            return formattedText.Width;
        }
Exemple #27
0
        internal TypefaceMap( 
            FontFamily           fontFamily,
            FontFamily           fallbackFontFamily,
            FontStyle            canonicalStyle,
            FontWeight           canonicalWeight, 
            FontStretch          canonicalStretch,
            bool                 nullFont 
            ) 
        {
            Invariant.Assert(fontFamily != null); 

            _fontFamilies = fallbackFontFamily == null ?
                 new FontFamily[] { fontFamily }
               : new FontFamily[] { fontFamily, fallbackFontFamily }; 

             _canonicalStyle   = canonicalStyle; 
             _canonicalWeight  = canonicalWeight; 
             _canonicalStretch = canonicalStretch;
             _nullFont         = nullFont; 
        }
Exemple #28
0
        internal string GetSubstringForWidth(string text, double width, FontFamily fontFamily,
            FontStyle fontStyle,
            FontWeight fontWeight, FontStretch fontStretch,
            double fontSize)
        {
            //Trace.WriteLine("  Path string too long... shortening.");
            if (width <= 0)
            {
                return "";
            }

            var length = text.Length;
            var testString = text;

            while (true)
            {
                var ft = new FormattedText(testString,
                    CultureInfo.CurrentCulture,
                    FlowDirection.LeftToRight,
                    new Typeface(fontFamily, fontStyle, fontWeight, fontStretch),
                    fontSize,
                    Brushes.Black);
                if (ft.Width <= width) break;

                // remove a bit.
                length--;
                testString = text.Substring(0, length);
            }

            // Do we need an ellipsis?
            if (testString != text)
            {
                // Strip off a character.
                testString = testString.Substring(0, testString.Length - 3);

                // Add an ellipsis.
                testString += "…";
            }

            return testString;
        }
 internal CompositeTypefaceMetrics(
     double      underlinePosition,
     double      underlineThickness,
     double      strikethroughPosition,
     double      strikethroughThickness,
     double      capsHeight,
     double      xHeight,
     FontStyle   style,
     FontWeight  weight,
     FontStretch stretch
     )           
 {
     _underlinePosition      = underlinePosition     != 0 ? underlinePosition      : UnderlineOffsetDefaultInEm;
     _underlineThickness     = underlineThickness     > 0 ? underlineThickness     : UnderlineSizeDefaultInEm;
     _strikethroughPosition  = strikethroughPosition != 0 ? strikethroughPosition  : StrikethroughOffsetDefaultInEm;
     _strikethroughThickenss = strikethroughThickness > 0 ? strikethroughThickness : StrikethroughSizeDefaultInEm;
     _capsHeight             = capsHeight             > 0 ? capsHeight             : CapsHeightDefaultInEm;
     _xHeight                = xHeight                > 0 ? xHeight                : XHeightDefaultInEm;
     _style                  = style;
     _weight                 = weight;
     _stretch                = stretch;
 }
Exemple #30
0
        public static FontStretch ToXwtFontStretch(SW.FontStretch value)
        {
            // No, SW.FontStretches is not an enum
            if (value == SW.FontStretches.UltraCondensed)
            {
                return(FontStretch.UltraCondensed);
            }
            if (value == SW.FontStretches.ExtraCondensed)
            {
                return(FontStretch.ExtraCondensed);
            }
            if (value == SW.FontStretches.Condensed)
            {
                return(FontStretch.Condensed);
            }
            if (value == SW.FontStretches.SemiCondensed)
            {
                return(FontStretch.SemiCondensed);
            }
            if (value == SW.FontStretches.SemiExpanded)
            {
                return(FontStretch.SemiExpanded);
            }
            if (value == SW.FontStretches.Expanded)
            {
                return(FontStretch.Expanded);
            }
            if (value == SW.FontStretches.ExtraExpanded)
            {
                return(FontStretch.ExtraExpanded);
            }
            if (value == SW.FontStretches.UltraExpanded)
            {
                return(FontStretch.UltraExpanded);
            }

            return(FontStretch.Normal);
        }
 public TextFormat(TextElement e)
 {
     FontFamily = e.FontFamily;
     FontSize = e.FontSize;
     FontStyle = e.FontStyle;
     FontWeight = e.FontWeight;
     FontStretch = e.FontStretch;
     if (e.Foreground is SolidColorBrush)
     {
         ForegroundColor = ((SolidColorBrush)e.Foreground).Color;
     }
     else
     {
         ForegroundColor = SystemColors.WindowTextColor;
     }
     if (e.Background is SolidColorBrush)
     {
         BackgroundColor = ((SolidColorBrush)e.Background).Color;
     }
     else
     {
         BackgroundColor = SystemColors.WindowColor;
     }
 }
Exemple #32
0
        internal static IFontFamily LookupFontFamilyAndFace(
            CanonicalFontFamilyReference canonicalFamilyReference, 
            ref FontStyle                style,
            ref FontWeight               weight, 
            ref FontStretch              stretch 
            )
        { 
            if (canonicalFamilyReference == null || object.ReferenceEquals(canonicalFamilyReference, CanonicalFontFamilyReference.Unresolved))
            {
                // no canonical name, e.g., because the friendly name was an empty string
                // or could not be canonicalized 
                return null;
            } 
 
            try
            { 
                FamilyCollection familyCollection;

                if (canonicalFamilyReference.LocationUri == null && canonicalFamilyReference.EscapedFileName == null)
                { 
                    // No explicit location; use the default family collection.
                    familyCollection = _defaultFamilyCollection; 
                } 
                else if (canonicalFamilyReference.LocationUri != null)
                { 
                    // Look in the location specified by the font family reference.
                    familyCollection = FamilyCollection.FromUri(canonicalFamilyReference.LocationUri);
                }
                else // canonicalFamilyReference.EscapedFileName != null 
                {
                    // Look in the specified file in the Windows Fonts folder 
                    // Note: CanonicalFamilyReference.EscapedFileName is safe to combine with Util.WindowsFontsUriObject because CanonicalFamilyReference guarantees that it will be a simple filename 
                    // without relative path or directory components.
                    Uri locationUri = new Uri(Util.WindowsFontsUriObject, canonicalFamilyReference.EscapedFileName); 
                    familyCollection = FamilyCollection.FromWindowsFonts(locationUri);
                }

                IFontFamily fontFamily = familyCollection.LookupFamily( 
                    canonicalFamilyReference.FamilyName,
                    ref style, 
                    ref weight, 
                    ref stretch
                ); 
                return fontFamily;
            }
            // The method returns null in case of malformed/non-existent fonts and we fall back to the next font.
            // Therefore, we can disable PreSharp warning about empty catch bodies. 
#pragma warning disable 6502
            catch (FileFormatException) 
            { 
                // malformed font file
            } 
            catch (IOException)
            {
                // canonical name points to a place that doesn't exist or can't be read for some reason
            } 
            catch (UnauthorizedAccessException)
            { 
                // canonical name points to a place caller doesn't have permission to access 
            }
            catch (ArgumentException) 
            {
                // canonical name points to a valid Uri that doesn't point to a well formed
                // OS local path
            } 
            catch (NotSupportedException)
            { 
                // canonical name points to a Uri that specifies an unregistered scheme 
            }
            catch (UriFormatException) 
            {
                // canonical name points to a malformed Uri
            }
#pragma warning restore 6502 
            // we want to fall back to the default fallback font instead of crashing
            return null; 
        } 
Exemple #33
0
        /// <summary> 
        /// Find the first valid IFontFamily, if any, for this FontFamily and sets the style, weight,
        /// and stretch to valies implied by the font family (e.g., "Arial Bold" implies FontWeight.Bold).
        /// </summary>
        internal IFontFamily FindFirstFontFamilyAndFace( 
            ref FontStyle   style,
            ref FontWeight  weight, 
            ref FontStretch stretch 
            )
        { 

            if (_familyIdentifier.Source == null)
            {
                Invariant.Assert(_firstFontFamily != null, "Unnamed FontFamily should have a non-null first font family"); 
                return _firstFontFamily;
            } 
 
            IFontFamily firstFontFamily = null;
 
            _familyIdentifier.Canonicalize();

            for (int i = 0, c = _familyIdentifier.Count; firstFontFamily == null && i < c; ++i)
            { 
                firstFontFamily = LookupFontFamilyAndFace(
                    _familyIdentifier[i], 
                    ref style, 
                    ref weight,
                    ref stretch); 
            }

            return firstFontFamily;
        } 
Exemple #34
0
        internal static bool FontStretchStringToKnownStretch(string s, IFormatProvider provider, ref FontStretch fontStretch)
        {
            switch (s.Length)
            {
            case 6:
                if (s.Equals("Normal", StringComparison.OrdinalIgnoreCase))
                {
                    fontStretch = FontStretches.Normal;
                    return(true);
                }
                if (s.Equals("Medium", StringComparison.OrdinalIgnoreCase))
                {
                    fontStretch = FontStretches.Medium;
                    return(true);
                }
                break;

            case 8:
                if (s.Equals("Expanded", StringComparison.OrdinalIgnoreCase))
                {
                    fontStretch = FontStretches.Expanded;
                    return(true);
                }
                break;

            case 9:
                if (s.Equals("Condensed", StringComparison.OrdinalIgnoreCase))
                {
                    fontStretch = FontStretches.Condensed;
                    return(true);
                }
                break;

            case 12:
                if (s.Equals("SemiExpanded", StringComparison.OrdinalIgnoreCase))
                {
                    fontStretch = FontStretches.SemiExpanded;
                    return(true);
                }
                break;

            case 13:
                if (s.Equals("SemiCondensed", StringComparison.OrdinalIgnoreCase))
                {
                    fontStretch = FontStretches.SemiCondensed;
                    return(true);
                }
                if (s.Equals("ExtraExpanded", StringComparison.OrdinalIgnoreCase))
                {
                    fontStretch = FontStretches.ExtraExpanded;
                    return(true);
                }
                if (s.Equals("UltraExpanded", StringComparison.OrdinalIgnoreCase))
                {
                    fontStretch = FontStretches.UltraExpanded;
                    return(true);
                }
                break;

            case 14:
                if (s.Equals("UltraCondensed", StringComparison.OrdinalIgnoreCase))
                {
                    fontStretch = FontStretches.UltraCondensed;
                    return(true);
                }
                if (s.Equals("ExtraCondensed", StringComparison.OrdinalIgnoreCase))
                {
                    fontStretch = FontStretches.ExtraCondensed;
                    return(true);
                }
                break;
            }
            int stretchValue;

            if (int.TryParse(s, NumberStyles.Integer, provider, out stretchValue))
            {
                fontStretch = FontStretch.FromOpenTypeStretch(stretchValue);
                return(true);
            }
            return(false);
        }
		public static void SetValueFontStretch(DependencyObject i, FontStretch v) => i.Set(SecondaryValueFontStretchProperty, v);
Exemple #36
0
        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 void SetHeaderFontStretch(UIElement element, FontStretch value)
 {
     element.SetValue(HeaderFontStretchProperty, value);
 }