【发布时间】:2020-08-26 14:28:58
【问题描述】:
我需要根据字体、字体大小和字体属性(粗体/斜体)等一些样式属性来测量字符串的宽度和高度。我该怎么做?
谢谢!
【问题讨论】:
标签: xamarin xamarin.forms
我需要根据字体、字体大小和字体属性(粗体/斜体)等一些样式属性来测量字符串的宽度和高度。我该怎么做?
谢谢!
【问题讨论】:
标签: xamarin xamarin.forms
在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 方法。
【讨论】: