samedi 25 novembre 2017

Delphi TCheckbox/TRadiobutton Autosize

I want dayamically created Checkboxes and Radiobuttons with a fixed Width (because they are aligned) to change their Heigth based on their containing text. My Checkboxes and Radiobuttons have WordWrap enabled. So I want to get something like the TLabel does, when AutoSize and WordWrap are enabled.

I've already managed to get close to this:

procedure TFMenu.Button1Click(Sender: TObject);
var
  ctr: Integer;
  hostingComponent: TComponent;
begin
  hostingComponent := Form1; { in my case a Frame or Panel or sth. }
  for ctr := 0 to pred(hostingComponent.ComponentCount) do
  begin
    if hostingComponent.Components[ctr] is TRadioButton { or TCheckBox } then
    begin
      with (hostingComponent.Components[ctr] as TRadioButton) do
      begin
        Height := 0; { if text or text Width changes this is useful }
        while (Height) * (Width - 32)
        <=
        (Canvas.TextHeight(Text) * 1.25 ) * Canvas.TextWidth(Text) do
        begin
          Height := Height + 1;
        end;
      end;
    end;
  end;
end;

This works something like acceptable for texts between 20 and 150 Characters, however I know this is very wrong and I don't know, what I am missing here. Multiplying Canvas.TextHeight by 1.25 made the text look okay for the length mentioned above, but I don't know why. Width - 32 is because of the size of the image of the checkbox/radiobutton, which is not the text I want to handle. (I guessed 32 would be right, it could differ in reality)

So my question is how to change the Heigth of those Components based on the containing text.

Also: How can I change my code to work as expected. The maths behind it should be correct, but the areas I use seem to be wrong as the area of the Checkbox/Radiobutton does not entirely contain text but end with some free space as the text is not block, but simply left-bounded.




Aucun commentaire:

Enregistrer un commentaire