-
Notifications
You must be signed in to change notification settings - Fork 981
Description
@Agorath suggested in #2006 it would be nice to have a way to implement snapping in draggable axis lines.
This issue will explore the different ways this may be achieved. An ideal solution would require no code modification to the existing library. The solution described below gets pretty close!#2006
Snap on Drop
This can be realized using existing code like this using the current library on NuGet.
public partial class Form1 : Form
{
ScottPlot.Plottable.VLine VLine1;
ScottPlot.Plottable.HLine HLine1;
double[] YSnapPositions = DataGen.Consecutive(11, 0.2, -1);
double[] XSnapPositions = DataGen.Consecutive(11, 5D);
public Form1()
{
InitializeComponent();
formsPlot1.Plot.AddSignal(DataGen.Sin(51), 1, Color.Black);
formsPlot1.Plot.AddSignal(DataGen.Cos(51), 1, Color.Gray);
VLine1 = formsPlot1.Plot.AddVerticalLine(23, Color.Blue);
VLine1.DragEnabled = true;
HLine1 = formsPlot1.Plot.AddHorizontalLine(.2, Color.Green);
HLine1.DragEnabled = true;
formsPlot1.PlottableDropped += FormsPlot1_PlottableDropped;
formsPlot1.Refresh();
}
private void FormsPlot1_PlottableDropped(object sender, EventArgs e)
{
(double mouseX, double mouseY) = formsPlot1.GetMouseCoordinates();
if (sender is ScottPlot.Plottable.VLine vline)
{
vline.X = GetClosestPosition(mouseX, XSnapPositions);
formsPlot1.Render();
}
else if (sender is ScottPlot.Plottable.HLine hline)
{
hline.Y = GetClosestPosition(mouseY, YSnapPositions);
formsPlot1.Render();
}
}
private double GetClosestPosition(double mouse, double[] snaps)
{
double closestDistance = double.MaxValue;
double closestPosition = double.MaxValue;
for (int i = 0; i < snaps.Length; i++)
{
double distance = Math.Abs(mouse - snaps[i]);
if (distance < closestDistance)
{
closestDistance = distance;
closestPosition = snaps[i];
}
}
return closestPosition;
}
}Remaining Challenge
If you try to use the PlottableDragged event handler, dragging plottables automatically calls Render, so while dragging a plottable using this method it's not possible to snap in real time without causing flickering. I'll see if I can solve this.
Welcome to ScottPlot!
Hi @Agorath 👋 welcome to the group (and the Discord! #1966). Even if we don't merge #2006 I'm happy for this question and I'm excited to figure out a solution since I doubt you're the only one interested in this topic 🚀

