Issyy Moola
Issyy Moola

Reputation: 137

How to convert a font(FontStyle, FontColor, FontSize) to a string

I want to save a font(FontStyle, FontColor, FontSize) in an sql database, to do this, i need to save this as a string. How do convert Tfont to TString?

Upvotes: 3

Views: 2887

Answers (3)

Anton Duzenko
Anton Duzenko

Reputation: 2596

I saw someone else's rather curious code doing this: Create a dummy control (TLabel), assign it your font and then save to a .dfm (binary, then text).

Upvotes: 0

IceCold
IceCold

Reputation: 21194

To store a font you only need the main properties of the font not ALL of them. I do this to save a font to INI file. You can easily convert it to a function that returns a string (TString):

procedure TMyIniFile.WriteFont(CONST Section, Ident: string; Value: TFont);
begin
  WriteString (Section, Ident + 'Name',    Value.Name);
  WriteInteger(Section, Ident + 'CharSet', Value.CharSet);
  WriteInteger(Section, Ident + 'Color',   Value.Color);
  WriteInteger(Section, Ident + 'Size',    Value.Size);
  WriteInteger(Section, Ident + 'Style',   Byte(Value.Style));
end;

Upvotes: 5

Denis Anisimov
Denis Anisimov

Reputation: 3317

Is it really necessary to store font params as string? I can offer you to store font as BLOB:

procedure SaveFontToStream(AStream: TStream; AFont: TFont);
var LogFont: TLogFont;
    Color: TColor;
begin
  if GetObject(AFont.Handle, SizeOf(LogFont), @LogFont) = 0 then
    RaiseLastOSError;
  AStream.WriteBuffer(LogFont, SizeOf(LogFont));
  Color := AFont.Color;
  AStream.WriteBuffer(Color, SizeOf(Color));
end;

procedure LoadFontFromStream(AStream: TStream; AFont: TFont);
var LogFont: TLogFont;
    F: HFONT;
    Color: TColor;
begin
  AStream.ReadBuffer(LogFont, SizeOf(LogFont));
  F := CreateFontIndirect(LogFont);
  if F = 0 then
    RaiseLastOSError;
  AFont.Handle := F;
  AStream.ReadBuffer(Color, SizeOf(Color));
  AFont.Color := Color;
end;

In any case you can convert stream to hex sequence.

Upvotes: 3

Related Questions