繁体   English   中英

在WPF装饰器中绘制虚线

[英]Draw dashed line in a WPF adorner

我在Web上发现了几篇关于在WPF中绘制虚线的文章。 但是,它们似乎围绕使用Line-class,它是WPF中的UIElement。 它是这样的:

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

现在,我在一个Adorner里面,我只能访问绘图上下文。 在那里,我或多或少地减少了绘图基元,画笔,笔,几何等。这看起来更像是:

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

我被困在如何在这个级别的API上做一个虚线。 我希望不是“逐一画出小线条”,而是我没有看到的其他东西......

查看Pen.DashStyle属性。 您可以使用DashStyles类的成员来提供一些预定义的短划线样式,也可以通过创建新的DashStyle实例来指定自己的短划线和间隙模式。

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

你不会坚持原始人。 如果您遵循此模式,则可以向装饰器添加任何内容。

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;
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM