How to save and restore font selections to a text file #163
Question
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; 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;
Tip by Paul Gertzen
Answer 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;
Tip by Rudy Velthuis
Answer 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;
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; begin Result := byte(Styles) end; function IntToFontStyles(Value: integer): TFontStyles; begin Result := TFontStyles(byte(Value)) end;
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 |