【问题标题】:Measuring textsize depending on style根据样式测量文本大小
【发布时间】:2020-08-26 14:28:58
【问题描述】:

我需要根据字体、字体大小和字体属性(粗体/斜体)等一些样式属性来测量字符串的宽度和高度。我该怎么做?
谢谢!

【问题讨论】:

    标签: xamarin xamarin.forms


    【解决方案1】:

    在Android 中,它提供getTextBounds 来检索文本边界框并存储到边界。界内回归。 https://developer.android.com/reference/android/graphics/Paint#getTextBounds(java.lang.CharSequence,%20int,%20int,%20android.graphics.Rect)

    在 Xamarin.Forms 中,我们可以使用依赖服务来做到这一点。

     public interface CalculateTextWidth
    {
        double calculateWidth(string text);
    }
    

    Android 实现:

    [assembly: Dependency(typeof(CalculateTextWidth_Android))]
    namespace App6.Droid
    {
    public class CalculateTextWidth_Android : CalculateTextWidth
    {
        public double calculateWidth(string text)
        {
            Rect bounds = new Rect();
            TextView textView = new TextView(Forms.Context);
            textView.Paint.GetTextBounds(text, 0, text.Length, bounds);
            var length = bounds.Width();
            return length / Resources.System.DisplayMetrics.ScaledDensity;
        }
    }
    }
    

    用法:

       private void Button_Clicked(object sender, EventArgs e)
        {
            var s = DependencyService.Get<CalculateTextWidth>().calculateWidth(label.Text);
        }
    

    【讨论】:

      【解决方案2】:

      我现在使用 SkiaSharps MeasureText 方法。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-05-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-01-23
        • 2014-05-04
        • 2016-06-17
        • 1970-01-01
        相关资源
        最近更新 更多