LiveCharts2 icon indicating copy to clipboard operation
LiveCharts2 copied to clipboard

Convert X/Y to Control Point

Open ajayre opened this issue 2 years ago • 2 comments

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

ajayre avatar Aug 15 '22 19:08 ajayre

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.

beto-rodriguez avatar Aug 20 '22 22:08 beto-rodriguez

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.

ajayre avatar Aug 23 '22 21:08 ajayre

This is already supported in the latest version of the library.

All the charts have the ScalePixelsToData and ScaleDataToPixels methods.

beto-rodriguez avatar Nov 06 '22 15:11 beto-rodriguez