Einzelnen Beitrag anzeigen

ASM

Registriert seit: 15. Aug 2004
165 Beiträge
 
Delphi 7 Enterprise
 
#5

AW: Länge eines Textes in Pixel ermitteln

  Alt 27. Nov 2011, 21:46
Die hättest du dir auch sparen können, indem du einfach mal nachgeschaut hättest wie Delphi das in TCanvas macht.
Das benötigt aber "A handle to the device context." [Zitat msdn microsoft].
Ein Label z.B. hat aber kein eigenes Handle, da es kein Fenster im Sinne von Windows ist.

Und was das betrift:
"Nach langer Recherche endlich was passendes gefunden. DT_CALCRECT heißt das Zauberwort. Für alle, die das selbe Problem haben:"
Das ist ja aber äußerst speziell und nicht universell verwendbar, allein schon deshalb, weil nicht alle beschriftbaren Objekte ein Canvas haben (wie z.B. Labels).

Dies hier sollte dagegen universell einsetzbar sein, egal ob für die Beschriftung von Label, Panel, Button, Statusbar, etc:
Code:
uses TypInfo;

type
  tTextSizeInPixel = record
    WidthInPixel, HeightInPixel: integer;
  end;
 
{...} 

function TForm1.GetTextSizeInPixel(obj: TObject; objFont: TFont; objText: string): tTextSizeInPixel;
var
  BM: TBitmap;
begin
  with result do
  begin
    widthInPixel := 0;
    heightInPixel := 0;
  end;
  // falls obj kein entspr. Property hat, ist alles weitere obsolet
  if GetPropInfo(Obj.ClassInfo, 'Font') = nil then exit;
  if GetPropInfo(Obj.ClassInfo, 'Caption') = nil then
    if GetPropInfo(Obj.ClassInfo, 'Text') = nil then exit;
  BM := TBitmap.Create;
  try
    BM.Canvas.Font := objFont;
    with result, BM.Canvas do
    begin
      widthInPixel := TextWidth(objText);
      heightInPixel := TextHeight(objText);
    end;
  finally
    BM.Free;
  end;
end;
Beispiel:
Code:
procedure TForm1.FormCreate(Sender: TObject);
begin
  // z.B.
  with Edit1 do
  begin
    Font.size := 14;
    Text := 'Forum Delphi-Praxis';
  end;
  with Label1 do
  begin
    Font.size := 12;
    Caption := 'GetTextSizeInPixel';
  end;
end;

procedure TForm1.Button1Click(Sender: TObject);
begin
    // mit einem Editfeld:
    with Edit1, GetTextSizeInPixel(Edit1, Font, text) do
      showmessage(format('Edit1 Text = %s'#13#10 +
        'Font Size: %d'#13#10 +
        'Text Höhe = %d Pixel, Weite = %d Pixel',
        [text, font.size, HeightInPixel, WidthInPixel]));

    // oder mit einem Label:
    with Label1, GetTextSizeInPixel(Label1, Font, caption) do
      showmessage(format('Label1 Caption = %s'#13#10 +
        'Font Size: %d'#13#10 +
        'Text Höhe = %d Pixel, Weite = %d Pixel',
        [caption, font.size, HeightInPixel, WidthInPixel]));
end;
  Mit Zitat antworten Zitat