コード例 #1
0
        public void SetFontProperties(string family, float lineHeight, float size, string style, string variant, int weight)
        {
            _fontFamily  = new System.Windows.Media.FontFamily(family);
            _fontStyle   = FontStyles.Normal;
            _fontStretch = FontStretches.Normal;

            if (style == "oblique")
            {
                _fontStyle = FontStyles.Oblique;
            }
            else if (style == "italic")
            {
                _fontStyle = FontStyles.Italic;
            }
            else //if (style == "normal")
            {
                _fontStyle = FontStyles.Normal;
            }

            if (weight >= 700)
            {
                _fontWeight = FontWeights.Bold;
            }
            else if (weight >= 400)
            {
                _fontWeight = FontWeights.Normal;
            }
            else
            {
                _fontWeight = FontWeights.Light;
            }

            _fontSize = size;

            // Compute the baseline offset by processing one character
            var textBlock = new System.Windows.Controls.TextBlock();
            var textRun   = new System.Windows.Documents.Run("k");

            textRun.FontFamily  = _fontFamily;
            textRun.FontSize    = _fontSize;
            textRun.FontWeight  = _fontWeight;
            textRun.FontStyle   = _fontStyle;
            textRun.FontStretch = _fontStretch;

            textBlock.FontFamily          = _fontFamily;
            textBlock.Padding             = new Thickness(0.0);
            textBlock.Margin              = new Thickness(0.0);
            textBlock.TextWrapping        = TextWrapping.NoWrap;
            textBlock.HorizontalAlignment = HorizontalAlignment.Left;
            textBlock.VerticalAlignment   = VerticalAlignment.Top;
            textBlock.Inlines.Add(textRun);
            textBlock.Measure(new Size(System.Double.PositiveInfinity, System.Double.PositiveInfinity));
            textBlock.Arrange(new Rect(textBlock.DesiredSize));

            _baseline = (float)textBlock.BaselineOffset;
        }
コード例 #2
0
        public static Size MeasureTextSize(string text, TextWrapping textWrapping, FontFamily fontFamily, FontStyle fontStyle, FontWeight fontWeight, FontStretch fontStretch, double fontSize, double maxWidth)
        {
            var textBlock = new System.Windows.Controls.TextBlock
            {
                Text         = text,
                TextWrapping = textWrapping,
                FontSize     = fontSize,
                FontFamily   = fontFamily,
                FontStretch  = fontStretch,
                FontStyle    = fontStyle,
                FontWeight   = fontWeight,
            };

            textBlock.Measure(new Size(maxWidth, Double.PositiveInfinity));
            textBlock.Arrange(new Rect(textBlock.DesiredSize));
            return(new Size(textBlock.ActualWidth, textBlock.ActualHeight));
        }