获取DrawingVisual属性

时间:2012-04-09 22:44:15

标签: .net wpf drawing drawingcontext

我使用此方法创建了一个DrawingVisual对象:

Private Function CreateDrawingVisualRectangle() As DrawingVisual

   Dim drawingVisual As New DrawingVisual() 
   Dim drawingContext As DrawingContext = drawingVisual.RenderOpen()
   Dim rect As New Rect(New Point(160, 100), New Size(320, 80))
   drawingContext.DrawRectangle(Brushes.LightBlue, New Pen(Brushes.Black, 0.5), rect)

   Return drawingVisual

End Function

有一种方法可以获得DrawingContext method绘制的形状及其属性吗?

即:

Dim MyVisual as DrawingVisual = CreateDrawingVisualRectangle()

Dim MyVisualType as MyType = MyVisual.GetDrawingType()
Dim MyBrush as Brush = MyVisual.GetDrawingBrush()
Dim MyPen as Pen = MyVisual.GetDrawingPen()
Dim MyRect as Rect = MyVisual.GetDrawingRect()
...

显然,我在上一个例子中使用的方法是实际上不存在的指示性方法,但我用它来获取MyVisual属性。

感谢。

1 个答案:

答案 0 :(得分:3)

您可以递归迭代DrawingVisual的Drawing属性提供的DrawingGroup中的Drawing个对象,如果子绘图是GeometryDrawing,请检查其Pen },BrushGeometry属性:

void InspectDrawings(DrawingVisual drawingVisual)
{
    InspectDrawings(drawingVisual.Drawing);
}

void InspectDrawings(DrawingGroup drawingGroup)
{
    foreach (Drawing drawing in drawingGroup.Children)
    {
        if (drawing is GeometryDrawing)
        {
            GeometryDrawing geometryDrawing = (GeometryDrawing)drawing;
            // inspect properties here
        }
        else if (drawing is DrawingGroup)
        {
            // recurse into sub-group
            InspectDrawings((DrawingGroup)drawing);
        }
    }
}

您现在可以检索几何类型并检查更多特殊属性。例如,如果它是RectangleGeometry,请检查其Rect属性。