public class CustomTooltipBehavior : ChartTooltipBehavior
{
public ChartSeries Series { get; set; }
protected override void OnTouchUp(float pointX, float pointY)
{
var datapoints = (Series as AreaSeries).GetDataPoints(new Rectangle(pointX - 50, pointY - 50, 100, 100));
List<Point> collection = new List<Point>();
if (datapoints != null && datapoints.Count > 0)
{
int i = 0;
foreach (var data in datapoints)
{
var d = data as Model;
var x = Chart.ValueToPoint(Chart.PrimaryAxis, d.XValue - 1); // minus 1 to ensure the position lies inside the segment area.
var y = Chart.ValueToPoint(Chart.SecondaryAxis, 45); // y value mentioned as static with in minimum of all data points.
collection.Add(new Point(x, y));
i++;
}
}
Point segmentPoint = new Point(pointX, pointY);
if (collection.Count > 0)
{
segmentPoint = FindNearestYPoint(collection, pointX);
}
this.Show((float)segmentPoint.X, (float)segmentPoint.Y, true);
}
private Point FindNearestYPoint(List<Point> collection, float pointX)
{
Point nearestPoint = collection[0];
double div = pointX > nearestPoint.X ? pointX - nearestPoint.X : nearestPoint.X - pointX;
int i = 1;
while (i < collection.Count)
{
var nextPoint = collection[i];
var temp_div = pointX > nextPoint.X ? pointX - nextPoint.X : nextPoint.X - pointX;
if (temp_div < div)
{
nearestPoint = nextPoint;
div = temp_div;
}
i++;
}
return nearestPoint;
}
} |