【发布时间】:2014-08-21 18:35:01
【问题描述】:
对 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);
}
【问题讨论】:
-
我们所说的距离左上角有多远,字体大小是多少?如果它只是 ~12pt 的几个像素,可能是由于字体的行高。另外,有什么特别的原因为什么您使用
FormattedText而不是让 WPF 只将字符串显示为TextBlocks? -
@MikeStrobel 嗨。它可以是许多像素。我正在根据笔划的高度创建一个字体大小。格式化文本的 LineHeight 属性似乎在 OnRender 中保持为 0。我正在使用 FormattedText 以希望获得更好看的转录。我希望我不必放弃它。
-
@MikeStrobel 作为一个粗略的近似,这非常接近: TranslateTransform t = new TranslateTransform(0, -0.19 * FontSize); dc.PushTransform(t); dc.DrawText(英尺,原点); dc.Pop();
标签: wpf xaml itemscontrol formatted-text