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