如何向箭头添加文字?

时间:2018-05-09 08:30:56

标签: c# wpf pathgeometry wpf-brushes

我目前正在制作一个箭头,其中包含一个显示偏移量的文本(此处为'Test')。 我的代码是:

Width = 200;
Length = 1000;
double arrowHeadWidth = Width;
double arrowHeadLength = Width / 2;
double arrowWidth = Width - arrowHeadWidth / 2;
double arrowLength = Length;
double centerY = Width / 2.0;

var figure = new PathFigure
{
   IsClosed = true,
   StartPoint = new Point(0, centerY - arrowWidth / 2.0)
};

figure.Segments.Add(new LineSegment(new Point(arrowLength - arrowHeadLength, centerY - arrowWidth / 2.0), true));
figure.Segments.Add(new LineSegment(new Point(arrowLength - arrowHeadLength, centerY - arrowHeadWidth / 2.0), true));
figure.Segments.Add(new LineSegment(new Point(arrowLength, centerY), true));
figure.Segments.Add(new LineSegment(new Point(arrowLength - arrowHeadLength, centerY + arrowHeadWidth / 2.0), true));
figure.Segments.Add(new LineSegment(new Point(arrowLength - arrowHeadLength, centerY + arrowWidth / 2.0), true));
figure.Segments.Add(new LineSegment(new Point(0, centerY + arrowWidth / 2.0), true));

var geometry = new PathGeometry();
geometry.Figures.Add(figure);

var borderPen = new Pen(Brushes.White, 10)
{
   LineJoin = PenLineJoin.Round
};

var arrowDrawing = new GeometryDrawing(Brushes.Transparent, borderPen, geometry);

FormattedText formattedText = new FormattedText(
  "Test",
  System.Globalization.CultureInfo.CurrentUICulture,
  FlowDirection.LeftToRight,
  new Typeface("Tahoma"),
  12,
  Brushes.Black);

  formattedText.MaxTextWidth = arrowLength - 40;
  formattedText.MaxTextHeight = arrowWidth - 10;
  Geometry textGeometry = formattedText.BuildGeometry(new System.Windows.Point(20, 5));

  GeometryDrawing textDrawing = new GeometryDrawing(Brushes.Red, new Pen(Brushes.Red, 1), textGeometry);

  var drawingGroup = new DrawingGroup();
  drawingGroup.Children.Add(arrowDrawing);
  drawingGroup.Children.Add(textDrawing);

  var brush = new DrawingBrush(drawingGroup);

但是我只显示了箭头。我究竟做错了什么? 如果我注释掉drawingGroup.Children.Add(arrowDrawing);行,我会显示文字。

任何建议都会有所帮助。提前谢谢,

修改 创建箭头

0 个答案:

没有答案