pointToPixel method
Converts chart data point value to logical pixel value.
The pointToPixel method takes chart data point value as input and returns logical pixel value.
Since this method is in the series controller, x and y-axis associated with this particular series will be considering for conversion value.
Widget build(BuildContext context) {
ChartSeriesController? _chartSeriesController;
return SfCartesianChart(
series: <LineSeries<SalesData, num>>[
LineSeries<SalesData, num>(
onRendererCreated: (ChartSeriesController controller) {
_chartSeriesController = controller;
},
onPointTap: (ChartPointDetails args) {
final CartesianChartPoint chartPoint =
CartesianChartPoint(
chartData[args.pointIndex!].x,
chartData[args.pointIndex!].y);
final Offset? pointLocation =
_chartSeriesController?.pointToPixel(chartPoint);
print('X location: ${pointLocation!.dx}');
print('Y location: ${pointLocation.dy}');
},
),
],
);
}
Implementation
Offset pointToPixel(CartesianChartPoint<D> point) {
if (point.x == null || point.y == null || seriesRenderer.xAxis == null) {
return Offset.zero;
}
final RenderChartAxis xAxis = seriesRenderer.xAxis!;
final D? x = point.x;
num pointX;
if (x is int) {
pointX = x;
} else {
if (xAxis is RenderDateTimeAxis) {
assert(x is DateTime);
pointX = (x as DateTime).millisecondsSinceEpoch;
} else if (xAxis is RenderDateTimeCategoryAxis) {
assert(x is DateTime);
pointX = xAxis.labels.indexOf((x as DateTime).millisecondsSinceEpoch);
} else if (xAxis is RenderCategoryAxis) {
assert(x is String);
pointX = xAxis.labels.indexOf(x.toString());
} else {
pointX = x as num;
}
}
final double pixelX = seriesRenderer.pointToPixelX(pointX, point.y!);
final double pixelY = seriesRenderer.pointToPixelY(pointX, point.y!);
return Offset(pixelX, pixelY);
}