How do I determine the height of a line of text in a TMemo programmatically?

前端 未结 4 1777
小蘑菇
小蘑菇 2020-12-22 01:21

I\'ve got a TMemo, and I want to always make it exactly high enough to display the number of lines it contains. Unfortunately, I don\'t quite know how to calculate that. I

4条回答
  •  情深已故
    2020-12-22 02:13

    You need to use a TCanvas for this. You can either create a TBitMap in the background and use its TCanvas (after assigning the Memo's Font property to the Bitmap.Canvas' one), or use a TCanvas from another component. Somthing like this:

    BMP:=TBitMap.Create;
    TRY
      BMP.Canvas.Font.Assign(Memo.Font);
      TotalHeight:=0;
      FOR LineNo:=1 TO Memo.Lines.Count DO INC(TotalHeight,BMP.Canvas.TextHeight(Memo.Lines[PRED(I)]))
    FINALLY
      FreeAndNIL(BMP)
    END;
    

    Edit:

    Or perhaps this one:

    BMP:=TBitMap.Create;
    TRY
      BMP.Canvas.Font.Assign(Memo.Font);
      LineHeight:=BMP.Canvas.TextHeight('Wq');
      TotalHeight:=Memo.Lines.Count*LineHeight
    FINALLY
      FreeAndNIL(BMP)
    END;
    

提交回复
热议问题