«« Site Rescued »»

While the site is still going to move from its current host, a new site will now take its place. More Info.

The new site may have less content, but the core will now remain. And it will now play nicely with phones! Keep an eye on the DelphiDabbler Blog for news.

» Help

How to save and restore font selections to a text file

I need to save and restore font selections to a text file. I was able to convert all the font attributes except for style to and from strings using one line expressions.

Answer 1

Here's one way of doing it:

function StyleToStr(Style: TFontStyles): String;
  SetLength(Result, 4);
  {T = true, S = false 83 is ordinal value of S, if true then S + 1 (84) = T}
  Result[1] := Char(Integer(fsBold In Style) + 83);
  Result[2] := Char(Integer(fsItalic In Style) + 83);
  Result[3] := Char(Integer(fsUnderline In Style) + 83);
  Result[4] := Char(Integer(fsStrikeOut In Style) + 83);
  {replace all S to F's if you like}
  Result := StringReplace(Result, 'S', 'F', [rfReplaceAll]);

function StrToStyle(Str: String): TFontStyles;
  Result := [];
  {T = true, S = false}
  if Str[1] = 'T' then
    Include(Result, fsBold);
  if Str[2] = 'T' then
    Include(Result, fsItalic);
  if Str[3] = 'T' then
    Include(Result, fsUnderLine);
  if Str[4] = 'T' then
    Include(Result, fsStrikeOut);

Tip by Paul Gertzen

Answer 2

I'd suggest this:

function StyleToStr(Style: TFontStyles): string;
  Chars: array [Boolean] of Char = ('F', 'T');
  SetLength(Result, 4);
  Result[1] := Chars[fsBold in Style];
  Result[2] := Chars[fsItalic in Style];
  Result[3] := Chars[fsUnderline in Style];
  Result[4] := Chars[fsStrikeOut in Style];

Tip by Rudy Velthuis

Answer 3

A more algorithmic approach:

function FontStylesToStr(Style: TFontStyles): string;
  I: TFontStyle;
  SetLength(Result, High(TFontStyle) + 1);
  for I := Low(TFontStyle) to High(TFontStyle) do
    if I in Style then
      Result[Ord(I) + 1] := 'F'
      Result[Ord(I) + 1] := 'T';
function StrToFontStyles(Str: string): TFontStyles;
  I: TFontStyle;
  Result := [];
  for I := Low(TFontStyle) to High(TFontStyle) do
    if Str[Ord(I) + 1] = 'T' then
      Include(Result, I);

Tip by Rudy Velthuis

Answer 4

May I propose that you save the font style using a numeric representation of the bit pattern. One special consideration during the conversion would be the size of the enumeration. That is, make sure you use an integer type that has the same boundary as the set type. For example, there are four possible font styles in TFontStyles, it would be stored as a byte.

function FontStylesToInt(Styles: TFontStyles): Integer;
  Result := byte(Styles)

function IntToFontStyles(Value: integer): TFontStyles;
  Result := TFontStyles(byte(Value))

If you are a purist, replace Integer with Byte.

Tip by Emerson A. Chen

Original resource: The Delphi Pool
Author: Various
Added: 2010-06-02
Last updated: 2010-06-02

« Return to contents »