首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >WPF。如何为DrawingContext获取TextBlock?

WPF。如何为DrawingContext获取TextBlock?
EN

Stack Overflow用户
提问于 2014-03-01 22:48:59
回答 2查看 2.3K关注 0票数 3

我有一个TextBlock。我想在里面画(在它当前的视觉范围内)。我需要DrawingContext。

我怎样才能得到DrawingContext?

(MSDN说,任何FrameworkElement都是Visual的后代,Visual提供了对呈现的支持。)但我找不到确切的方法)

请注意-此代码将被每秒调用几次。我正在寻找最有效的解决方案(这就是我首先使用DrawingContext的原因)。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2014-03-03 11:10:48

我所做的:我写了我自己的装饰器,装饰了文本块,使用OnRender获取了DrawingContext,我将文本直接写入到装饰器,并在每次更改时使可视化无效。

性能的提升(使用Ants仔细测量)比直接将文本写入文本块()要好4.5倍,甚至比绑定字符串属性还要好。

票数 2
EN

Stack Overflow用户

发布于 2014-03-01 23:29:21

为什么不将TextBlock覆盖在画布上并绘制到画布上呢?

XAML

代码语言:javascript
复制
 <Grid>
    <Canvas Background='Orange'
            x:Name='drawingCanvas'
            Width='{Binding ActualWidth, ElementName=textblock1, Mode=OneWay}'
            Height='{Binding ActualHeight, ElementName=textblock1, Mode=OneWay}' />

    <TextBlock Text='Example'
               x:Name='textblock1'
               HorizontalAlignment='Center'
               VerticalAlignment='Center'
               FontSize='40' />
  </Grid>

代码语言:javascript
复制
public MainWindow() {
      InitializeComponent();
      this.Loaded += MainWindow_Loaded;
      _timer.Interval = TimeSpan.FromMilliseconds(100);
      _timer.Start();
      _timer.Tick += _timer_Tick;
    }

    private void _timer_Tick(object sender, EventArgs e) {
      var newX = _bezierSeg.Point1.X + .1;
      _bezierSeg.Point1 = new Point(Math.Sin(newX) * 12, 0);
    }

    private DispatcherTimer _timer = new DispatcherTimer();

    private BezierSegment _bezierSeg = new BezierSegment();

    private void MainWindow_Loaded(object sender, RoutedEventArgs e) {
      var arcPath = new Path();
      var figure = new PathFigure();

      figure.StartPoint = new Point(0, 0);
      var Point1 = new Point(textblock1.ActualHeight, 0);
      var Point2 = new Point(textblock1.ActualWidth - 30, textblock1.ActualHeight - 20);
      var Point3 = new Point(textblock1.ActualWidth, textblock1.ActualHeight);

      _bezierSeg.Point1 = Point1;
      _bezierSeg.Point2 = Point2;
      _bezierSeg.Point3 = Point3;

      var myPathSegmentCollection = new PathSegmentCollection();

      myPathSegmentCollection.Add(_bezierSeg);
      figure.Segments = myPathSegmentCollection;

      var pathCollection = new PathFigureCollection();
      pathCollection.Add(figure);

      var pathGeometry = new PathGeometry();
      pathGeometry.Figures = pathCollection;

      arcPath.Stroke = new SolidColorBrush(Colors.Red);
      arcPath.Fill = new SolidColorBrush(Colors.Yellow);
      arcPath.StrokeThickness = 2;

      arcPath.Data = pathGeometry;
      drawingCanvas.Children.Add(arcPath);
    }
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/22121434

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档