根据样式测量文本大小



我需要根据一些样式属性来测量字符串的宽度和高度,如font、fontsize和fontattributes(粗体/斜体(。我该怎么做
谢谢!

在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);
}

我现在使用SkiaSharps MeasureText方法。

最新更新