C# 根据文本获取Text宽高

var textSize = GetTextSize(txtSentence.Text,
                txtSentence.FontFamily,
                txtSentence.FontStyle,
                txtSentence.FontWeight,
                txtSentence.FontStretch,
                txtSentence.FontSize,
                txtSentence.MaxWidth,
                32);

var textSize = GetTextSize(txtSentenceChinese.Text,
                txtSentenceChinese.FontFamily,
                txtSentenceChinese.FontStyle,
                txtSentenceChinese.FontWeight,
                txtSentenceChinese.FontStretch,
                txtSentenceChinese.FontSize,
                txtSentenceChinese.MaxWidth);
/// <summary>
/// 根据文本获取Text宽高
/// </summary>
/// <param name="text">文本</param>
/// <param name="font_family">字体</param>
/// <param name="font_style">字体样式</param>
/// <param name="font_weight">字体重量</param>
/// <param name="font_stretches">字体横纵比</param>
/// <param name="font_size">字体大小</param>
/// <param name="max_width">最大宽度</param>
/// <param name="line_height">行高</param>
/// <returns></returns>
private Size GetTextSize(string text,
	FontFamily font_family,
	FontStyle font_style,
	FontWeight font_weight,
	FontStretch font_stretches,
	double font_size,
	double max_width = 0,
	double line_height = 0)
{
	var formattedText = new FormattedText(text,
	CultureInfo.CurrentUICulture,
	FlowDirection.LeftToRight,
	new Typeface(font_family, font_style, font_weight, font_stretches),
	font_size,
	Brushes.Black);
	
	if (max_width != 0)
	formattedText.MaxTextWidth = max_width;
	if (line_height != 0)
	formattedText.LineHeight = line_height;
	
	return new Size(formattedText.Width, formattedText.Height);
}

这样可以提前知晓文本在UI中的大小,并提前设置大小。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值