3

我正在使用 WPF 在绘图程序中为线条制作装饰器。Line 是在代码隐藏中绘制的,然后用我的自定义 Adorner 进行装饰,称为LineAdorner. 我已经设法使用 aThumb作为 Line 的起点和终点。我的问题是关于起点和终点的拇指排列。我认为问题出在方法ArrangeOverride上,应该在哪里安排带有起点和终点的拇指。我找不到合适的数量来减去或添加Rect XandY参数。我怎样才能找到这些值以始终将拇指与线的点排列在一起?我的自定义装饰器的代码是这样的:

public class LineAdorner : Adorner { private Point start; private Point end; private Thumb startThumb; private Thumb endThumb; private Line selectedLine; private VisualCollection visualChildren; // Constructor public LineAdorner(UIElement adornedElement) : base(adornedElement) { visualChildren = new VisualCollection(this); startThumb = new Thumb { Cursor = Cursors.Hand, Width = 10, Height = 10, Background = Brushes.Green }; endThumb = new Thumb { Cursor = Cursors.Hand, Width = 10, Height = 10, Background = Brushes.BlueViolet }; startThumb.DragDelta += StartDragDelta; endThumb.DragDelta += EndDragDelta; visualChildren.Add(startThumb); visualChildren.Add(endThumb); selectedLine = AdornedElement as Line; } // Event for the Thumb Start Point private void StartDragDelta(object sender, DragDeltaEventArgs e) { Point position = Mouse.GetPosition(this); selectedLine.X1 = position.X; selectedLine.Y1 = position.Y; } // Event for the Thumb End Point private void EndDragDelta(object sender, DragDeltaEventArgs e) { Point position = Mouse.GetPosition(this); selectedLine.X2 = position.X; selectedLine.Y2 = position.Y; } protected override int VisualChildrenCount { get { return visualChildren.Count; } } protected override Visual GetVisualChild(int index) { return visualChildren[index]; } protected override void OnRender(DrawingContext drawingContext) { if (AdornedElement is Line) { selectedLine = AdornedElement as Line; start = new Point(selectedLine.X1, selectedLine.Y1); end = new Point(selectedLine.X2, selectedLine.Y2); } } protected override Size ArrangeOverride(Size finalSize) { var startRect = new Rect(selectedLine.X1, selectedLine.Y1, ActualWidth, ActualHeight); startThumb.Arrange(startRect); var endRect = new Rect(selectedLine.X2, selectedLine.Y2, ActualWidth, ActualHeight); endThumb.Arrange(endRect); return finalSize; } }

4

1 回答 1

3

在你的 ArrangeOverride 中试试这个。您可以摆脱“开始”和“结束”变量,并且不需要覆盖 OnRender,因为如果您告诉拇指它们需要在哪里,您的拇指将呈现自己。

    protected override Size ArrangeOverride(Size finalSize)
{
    selectedLine = AdornedElement as Line;

    double left = Math.Min(selectedLine.X1, selectedLine.X2);
    double top = Math.Min(selectedLine.Y1, selectedLine.Y2);

    var startRect = new Rect(selectedLine.X1 - (startThumb.Width / 2), selectedLine.Y1 - (startThumb.Width / 2), startThumb.Width, startThumb.Height);
    startThumb.Arrange(startRect);

    var endRect = new Rect(selectedLine.X2 - (endThumb.Width / 2), selectedLine.Y2 - (endThumb.Height / 2), endThumb.Width, endThumb.Height);
    endThumb.Arrange(endRect);

    return finalSize;
}

您在 Thumbs 上设置了明确的大小,因此必须在 Arrange 中进行维护。此外,您需要减去拇指宽度和高度的一半以使端点居中。

由于画布和形状的性质,您需要减去线的“真实”左侧和顶部值,因为与线不同,装饰者不会从画布的左上角绘制自己。除了使用 Canvasses 之外,这不应该是必需的。

于 2012-05-30T20:44:24.380 回答