3

我有一个DrawingVisual对象,我想更改它的填充和描边。

我试过这个填充:

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); 我会得到一个奇怪的效果:如果我第一次更改填充没有任何反应,而第二次填充正确更改而不改变图形的位置。

我能怎么做?

4

3 回答 3

2

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

于 2012-05-09T08:06:32.340 回答
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;
        }
    }
}
于 2013-05-20T00:31:11.490 回答
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();
            }
        }
    }
}
于 2012-08-20T07:48:06.517 回答