在WPF装饰器中绘制虚线

11

我在网上找到了几篇关于在WPF中绘制虚线的文章。但是,它们似乎都是围绕着在WPF中使用UIElement的Line类来实现的。 大概是这样:

Line myLine = new Line();
DoubleCollection dashes = new DoubleCollection();
dashes.Add(2);
dashes.Add(2);
myLine.StrokeDashArray = dashes;

现在,我在一个装饰器内部,只能访问绘图上下文。在那里,我基本上只能使用绘图原语、画刷、笔、几何等。这看起来更像这样:

var pen = new Pen(new SolidColorBrush(Color.FromRgb(200, 10, 20)), 2);
drawingContext.DrawLine(pen, point1, point2);

我卡在了如何在此级别的 API 上绘制虚线上。我希望这不是“一条一条地画小线条”,而是其他我还没有见过的方法...

2个回答

25
看一下Pen.DashStyle属性,你可以使用DashStyles类的成员来获取一些预定义的虚线样式,或者创建一个新的DashStyle实例来指定自己的虚线和间隙模式。请访问以下链接以获取更多信息:Pen.DashStyleDashStylesDashStyle
var pen = new Pen(new SolidColorBrush(Color.FromRgb(200, 10, 20)), 2);
pen.DashStyle = DashStyles.Dash;
drawingContext.DrawLine(pen, point1, point2);

1
哦,就是这样,我不知怎么错过了那个属性。现在德国的温度超过35摄氏度 :) - flq

1

你不必局限于基本元素。如果你按照这种模式,你可以将任何东西添加到装饰器中。

public class ContainerAdorner : Adorner
{
    // To store and manage the adorner's visual children.
    VisualCollection visualChildren;

    // Override the VisualChildrenCount and GetVisualChild properties to interface with 
    // the adorner's visual collection.
    protected override int VisualChildrenCount { get { return visualChildren.Count; } }
    protected override Visual GetVisualChild(int index) { return visualChildren[index]; }

    // Initialize the ResizingAdorner.
    public ContainerAdorner (UIElement adornedElement)
        : base(adornedElement)
    {
        visualChildren = new VisualCollection(this);
        visualChildren.Add(_Container);
    }
    ContainerClass _Container= new ContainerClass();

    protected override Size ArrangeOverride(Size finalSize)
    {
        // desiredWidth and desiredHeight are the width and height of the element that's being adorned.  
        // These will be used to place the Adorner at the corners of the adorned element.  
        double desiredWidth = AdornedElement.DesiredSize.Width;
        double desiredHeight = AdornedElement.DesiredSize.Height;

        FrameworkElement fe;
        if ((fe = AdornedElement as FrameworkElement) != null)
        {
            desiredWidth = fe.ActualWidth;
            desiredHeight = fe.ActualHeight;
        }

        _Container.Arrange(new Rect(0, 0, desiredWidth, desiredHeight));

        return finalSize;
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接