代码之家  ›  专栏  ›  技术社区  ›  flq

在WPF装饰器中绘制虚线

  •  11
  • flq  · 技术社区  · 14 年前

    我在网上找到了几篇关于在WPF中绘制虚线的文章。然而,它们似乎是围绕使用line类(wpf中的uielement)而展开的。就像这样:

    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 回复  |  直到 12 年前
        1
  •  22
  •   Samuel Jack    14 年前

    看看 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);
    
        2
  •  1
  •   Lee Louviere    12 年前

    你不必拘泥于原语。如果遵循此模式,可以向装饰器添加任何内容。

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