在绘图Visual

时间:2019-12-03 01:59:38

标签: c# wpf drawingcontext

OnRender方法中,我可以在Draw区域中解决这个问题:

protected override void OnRender(DrawingContext drawingContext)
{
    var drawing = new DrawingVisual();
    using (drawingContext = drawing.RenderOpen())
    {
        var grid = new Grid() { Width = Width, Height = Height, Background = new SolidColorBrush(Colors.Green) };
        var text = new TextBlock() 
        { 
            Text = Height.ToString("N2"), 
            Foreground = new SolidColorBrush(Colors.White), 
            LayoutTransform = new RotateTransform(-90),
            VerticalAlignment = VerticalAlignment.Top,
            Margin = new Thickness(0, 5, 0, 0)
        };
        grid.Children.Add(text);

        #region Draw    
        grid.Measure(new Size(Width, Height));
        var brush = new VisualBrush(grid);
        var pen = new Pen(new SolidColorBrush(Colors.Blue), 1);
        var rect = new Rect(grid.DesiredSize);
        drawingContext.DrawRectangle(brush, pen, rect);
        #endregion
    }
    Visual = drawing;
}

或者我可以这样做:

#region Draw
grid.Measure(new Size(Width, Height));
grid.Arrange(new Rect(grid.DesiredSize));
var brush = new VisualBrush(grid);
var pen = new Pen(new SolidColorBrush(Colors.Blue), 1);
//var rect = new Rect(grid.DesiredSize);
var rect = new Rect(new Size(grid.ActualWidth, grid.ActualHeight));
dc.DrawRectangle(brush, pen, rect);
#endregion

显然,输出没有区别!我是否可以避免总是调用Arrange方法,或者在某些情况下也必须调用该方法?

0 个答案:

没有答案