2008. január 7., hétfő

How to save and restore font selections to a text file


Problem/Question/Abstract:

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:

Solve 1:

Here's one way of doing it:

function StyleToStr(Style: TFontStyles): string;
begin
  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]);
end;

function StrToStyle(Str: string): TFontStyles;
begin
  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);
end;


Solve 2:

I'd suggest this:

function StyleToStr(Style: TFontStyles): string;
const
  Chars: array[Boolean] of Char = ('F', 'T');
begin
  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];
end;


Solve 3:

A more algorithmic approach:

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

function StrToFontStyles(Str: string): TFontStyles;
var
  I: TFontStyle;
begin
  Result := [];
  for I := Low(TFontStyle) to High(TFontStyle) do
    if Str[Ord(I) + 1] = 'T' then
      Include(Result, I);
end;


Solve 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;
begin
  Result := byte(Styles)
end;

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

If you are a purist, replace 'integer's with 'byte's

Nincsenek megjegyzések:

Megjegyzés küldése