Setting custom position for chart legend
Posted: Fri Jul 21, 2017 4:21 pm
In a project I’m working on, I have need for the legend on a chart to be completely centered in the middle of the chart. Unfortunately, setting TChart.Legend.Left and TChartLegend.Top using the 50% strategy does not work since this centers the top left corner of the legend and not the center of the legend.
So to try to get this to work, I tried setting “Chart1.Legend.CustomPosition := True” in the OnCreate of my form. And then I used the following OnGetLegendRect procedure for Chart1.
When I step through the debugger, Left and Right are correctly being set. However, when the form actually displays, it does not reflect that, and they are both set to zero with the legend in the top left corner.
Can you please help me understand what I might be doing wrong with this method?
Alternatively, I tried the following:
However, that only moves the legend itself and not the items in it. I see from the documentation that I am supposed to use OnGetLegendPosition but I’m not sure how to use X, Y, and XColor to do that. Could you please help with that?
Thanks!
So to try to get this to work, I tried setting “Chart1.Legend.CustomPosition := True” in the OnCreate of my form. And then I used the following OnGetLegendRect procedure for Chart1.
Code: Select all
procedure TfrmMain.Chart1GetLegendRect(Sender: TCustomChart; var Rect: TRect);
begin
Sender.Legend.Left := Trunc((Sender.Width – (Rect.Right – Rect.Left)) / 2);
Sender.Legend.Right := Trunc((Sender.Height – (Rect.Bottom – Rect.Top)) / 2);
end;
Can you please help me understand what I might be doing wrong with this method?
Alternatively, I tried the following:
Code: Select all
procedure TfrmMain.Chart1GetLegendRect(Sender: TCustomChart; var Rect: TRect);
var
iLegendWidth, iLegendHeight: Integer;
begin
iLegendWidth := Rect.Right – Rect.Left;
iLegendHeight := Rect.Bottom – Rect.Top;
Rect.Left := Trunc((Sender.Width – iLegendWidth) / 2);
Rect.Right := Rect.Left + iLegendWidth;
Rect.Top := Trunc((Sender.Height – iLegendHeight) / 2);
Rect.Bottom := Rect.Top + iLegendHeight;
end;
Thanks!