如何解决根据样式测量文本大小
我需要根据字体,字体大小和字体属性(粗体/斜体)等一些样式属性来测量字符串的宽度和高度。我该怎么办?
谢谢!
解决方法
在Android中,它提供了getTextBounds
来检索文本边界框并存储到边界。返回界限。
https://developer.android.com/reference/android/graphics/Paint#getTextBounds(java.lang.CharSequence,%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,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方法。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。