LiveCharts2
LiveCharts2 copied to clipboard
Convert X/Y to Control Point
Sorry if this functionality is in there and I have missed it but I found the need for a function that converts cartesian chart X/Y axis values to a UI control X/Y pixel location. This helps with re-drawing custom elements when zooming and panning. Here is my code. Would be cool if this was added as a public function to CartesianChart for WinForms.
/// <summary>
/// Converts a value on the X and Y axis into a control X/Y value in pixels
/// </summary>
/// <param name="ChartX">X axis value to convert</param>
/// <param name="ChartY">Y axis value to convert</param>
/// <param name="XAxisIndex">Index of X axis to use</param>
/// <param name="YAxisIndex">Index of Y axis to use</param>
/// <returns>[X,Y] in pixels relative to chart control</returns>
private double[] ChartToUIPoint
(
double ChartX,
double ChartY,
int XAxisIndex = 0,
int YAxisIndex = 0
)
{
CartesianChart<SkiaSharpDrawingContext> CChart = (CartesianChart<SkiaSharpDrawingContext>)(Chart.CoreChart);
var xAxis = CChart.XAxes[XAxisIndex];
var yAxis = CChart.YAxes[YAxisIndex];
var xScaler = new Scaler(CChart.DrawMarginLocation, CChart.DrawMarginSize, xAxis);
var yScaler = new Scaler(CChart.DrawMarginLocation, CChart.DrawMarginSize, yAxis);
return new double[] { xScaler.ToPixels(ChartX), yScaler.ToPixels(ChartY) };
}
Hi!
You are almost there!
The Scaler
class povides both methods.
Scaler.ToChartValues()
: it takes a value [in pixels] and returns a a value in the chart values scale.
Scaler.ToPixels()
: it takes a value [in chart values scale] and returns a value in pixels.
Thanks. The point (I poorly made) is that CartesianChart has a function for pixels-> control so I think it would be more user-friendly for the same class to also have the inverse function.
This is already supported in the latest version of the library.
All the charts have the ScalePixelsToData
and ScaleDataToPixels
methods.