c# - 有没有办法计算字体的真实高度?
问题描述
我遇到过使用垂直居中无法正确对齐文本的情况。尤其是当字体较大时(即 40)。我可以通过在顶部应用负边距来修复它,但是有没有办法以编程方式计算边距的数量?我尝试获取 FormattedText,但数字与屏幕上绘制的内容不匹配。
<Border BorderBrush="Black" BorderThickness="1,1,1,1" Width="46" Height="46" UseLayoutRounding="True" SnapsToDevicePixels="True">
<TextBlock FontFamily="Gadugi" Margin="0,-4,0,0" FontSize="36" Text="1" HorizontalAlignment="Center" VerticalAlignment="Center" />
</Border>
-4 修复了这种情况,但我将如何明智地计算 -4 代码?因为它在每个字体/每个字体大小的基础上都不同。
这些数字似乎与 FormattedText 中的数字不匹配。
解决方案
您可以尝试使用这样的几何变换:
FormattedText text = new FormattedText("Your text",
CultureInfo.CurrentCulture, FlowDirection.LeftToRight,
new Typeface("Arial"), 20, Brushes.Black);
Geometry geometry = text.BuildGeometry(new Point());
double height = geometry.Bounds.Bottom - geometry.Bounds.Top;
但是,这将导致您输入的字符串的高度。这意味着“abc”的高度比“ABC”短,“ABC”比“Ay”短
推荐阅读
- java - 无法在“/Library/Java/JavaVirtualMachines/jdk-15.0.1.jdk/Contents/Home/bin/apt”中找到可执行文件
- javascript - Firebase Firestore / Realtime DB:只允许写入特定的管理员用户
- android - 更改android中的通知默认图标?
- masstransit - 如何配置具有特定消息类型的过滤器?
- javascript - 在 Typescript 中将字符串消息拆分为数组
- f# - 制作 bprintfn (StringBuilder.AppendLine vs Append)
- java - 如何使用 PostgreSQL 设置 JNDI 数据源?
- c - Uint32_t 的可变字节数
- android - 如何在没有系统确认对话框的情况下删除 Android 11 (API 30) 上的文件?
- oracle - Oracle Apex Interactive Grid Master 多选到详细信息