2

对 XAML 使用带有 ItemsControl 的 MVVM 模式,我试图将 FormattedText 字符串的左上墨点准确定位在指定矩形的左上角。(矩形由 InkAnalyzer.Location.GetBounds() 给出)。

由于我无法弄清楚(或在 Google 上找到)的原因,FormattedText 字符串始终位于矩形左上角的右下角,距离似乎与用于打印的字体大小成正比。

如何实现 FormattedText 的定位以击中矩形的左上角?

任何帮助是极大的赞赏。

XAML

<ItemsControl 
                ItemsSource="{Binding Transcription}"
                >
                <ItemsControl.ItemsPanel>
                    <ItemsPanelTemplate>
                        <Canvas 
                            Background="Transparent"
                             Width="{x:Static h:Constants.widthCanvas}" 
                             Height="{x:Static h:Constants.heightCanvas}" 
                             />
                    </ItemsPanelTemplate>
                </ItemsControl.ItemsPanel>             
 </ItemsControl>

C#

 private ObservableCollection<StringViewModel> transcription = new ObservableCollection<StringViewModel>();
    public ObservableCollection<StringViewModel> Transcription
    {
        get
        {
            return transcription;
        }
    }


public class StringViewModel : FrameworkElement, INotifyPropertyChanged
{
    public StringViewModel(
        Point topleft, 
        string text, 
        double fontsize, 
        SolidColorBrush brush, 
        double linewidth, 
        double columnheight,
        Func<FormattedText,FormattedText> f)    
    {
        this.text = text;
        this.FontSize = fontsize * (72.0/96.0);     
        this.color = brush;
        this.origin = topleft;
        this.origin_X = topleft.X;
        this.origin_Y = topleft.Y;
        this.maxtextwidth = linewidth * (72.0/96.0);
        this.maxtextheight = columnheight ;
        this.f = f;
    }

    protected override void OnRender(DrawingContext dc)
    {

        FormattedText ft = new FormattedText(
            text, 
            CultureInfo.CurrentCulture, 
            FlowDirection.LeftToRight,
            new Typeface(new FontFamily("Segoe Script"), FontStyles.Italic, FontWeights.Normal, FontStretches.Normal), 
            FontSize, 
            color);

        ft.TextAlignment = TextAlignment.Left;

        ft.MaxTextWidth = maxtextwidth;
        ft.MaxTextHeight = maxtextheight;


        dc.DrawText(ft, origin);
    }
4

1 回答 1

3

我注意到 Segoe 系列字体在度量中往往有相当大的间距。对 16 像素(72 dpi 时为 12 像素)的 Segoe 脚本进行快速测试显示,在较高字形的顶部和边界框之间有大约 5 像素的填充。

线高示例

在上面的示例中,每个文本块都位于粉红色边框的左上角。您可以在第一行看到额外的垂直空间,我怀疑它重现了您在自己的代码中看到的内容。

将 设置LineHeight为字体大小会消除额外的空间,但会剪掉一些较高的字形。我的实验表明,a LineHeightof1.25 * FontSize往往是这种特定字体的理想选择,如第三行所示。它还保持足够的间距以显示多行文本。

顺便说一句,您可能希望将字体嵌入您的应用程序并通过其资源名称引用它,而不是简单地指定字体名称并希望您的用户安装它(但请务必检查许可详细信息)。

于 2014-08-21T10:04:17.797 回答