如何更改DrawingVisual填充和描边

时间:2012-05-09 07:22:48

标签: .net wpf drawing fill stroke

我有一个DrawingVisual对象,我想改变它的填充和中风。

我为Fill试过这个:

DrawingVisual MyDrawing = new DrawingVisual();
SetFill(Brushes.Red, MyDrawing.Drawing);

SetFill的位置:

private void SetFill(Brush fill, DrawingGroup group)
{
    foreach (Drawing drw in group.Children)
    {
        if (drw is DrawingGroup)
            SetFill(fill, drw as DrawingGroup);
        else if (drw is GeometryDrawing)
        {
            GeometryDrawing geo = drw as GeometryDrawing;
            geo.Brush = fill;

            using (DrawingContext context = MyDrawing.RenderOpen())
            {
                context.DrawDrawing(group);
            }
        }
    }
}

但是这样可能会发生我的DrawingVisual被绘制到不同的位置,就好像转换没有被应用更多(对于MyDrawing)。

另外,如果我更改此说明:context.DrawDrawing(group); 与另一个:context.DrawDrawing(MyDrawing.Drawing); 我得到一个奇怪的效果:如果我第一次更改填充没有任何反应,而第二次填充正确更改而不改变图形的位置。

我该怎么办?

3 个答案:

答案 0 :(得分:2)

您确实不需要重新绘制视觉效果。 这应该有用。

private void SetFill(Brush fill, DrawingGroup group)
{
    foreach (Drawing drw in group.Children)
    {
        if (drw is DrawingGroup)
            SetFill(fill, drw as DrawingGroup);
        else if (drw is GeometryDrawing)
        {
            GeometryDrawing geo = drw as GeometryDrawing;
            geo.Brush = fill; // For changing FILL

            // We have to set Pen properties individually.
            // It does not work if we assign the whole "Pen" instance.
            geo.Pen.Brush = fill; 
            geo.Pen.Thickness = 1.0;
        }
    }
}

答案 1 :(得分:1)

解决问题的一种更简单的方法(动态更改填充)是为所有填充使用自己的SolidColorBrush,并在需要时更改其Color

答案 2 :(得分:1)

可能你已经解决了这个问题,但这是我可能同样的解决方案。我有自己的DrawingVisual。它是新鲜的,并没有经过严格测试的代码,但现在它的工作非常好:

public class MyDrawingVisual : DrawingVisual
{
    private bool myIsSelected = false;

    public VillageInfo VillageInfo { get; set; }

    public bool IsSelected 
    {
        get { return myIsSelected; }
        set
        {
            if (myIsSelected != value)
            {
                myIsSelected = value;

                // Retrieve the DrawingContext in order to create new drawing content.
                DrawingContext drawingContext = this.RenderOpen();

                // Create a rectangle and draw it in the DrawingContext.
                Rect rect = new Rect(new System.Windows.Point(VillageInfo.X + 0.1, VillageInfo.Y + 0.1), new System.Windows.Size(0.9, 0.9));
                drawingContext.DrawRectangle(new SolidColorBrush(myIsSelected ? Colors.White : VillageInfo.Color), (System.Windows.Media.Pen)null, rect);

                // Persist the drawing content.
                drawingContext.Close();
            }
        }
    }
}