Author: Jonas Bilinkevicius
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:
1 function StyleToStr(Style: TFontStyles): string;
2 begin
3 SetLength(Result, 4);
4 {T = true, S = false 83 is ordinal value of S, if true then S + 1 (84) = T}
5 Result[1] := Char(Integer(fsBold in Style) + 83);
6 Result[2] := Char(Integer(fsItalic in Style) + 83);
7 Result[3] := Char(Integer(fsUnderline in Style) + 83);
8 Result[4] := Char(Integer(fsStrikeOut in Style) + 83);
9 {replace all S to F's if you like}
10 Result := StringReplace(Result, 'S', 'F', [rfReplaceAll]);
11 end;
12
13 function StrToStyle(Str: string): TFontStyles;
14 begin
15 Result := [];
16 {T = true, S = false}
17 if Str[1] = 'T' then
18 Include(Result, fsBold);
19 if Str[2] = 'T' then
20 Include(Result, fsItalic);
21 if Str[3] = 'T' then
22 Include(Result, fsUnderLine);
23 if Str[4] = 'T' then
24 Include(Result, fsStrikeOut);
25 end;
Solve 2:
I'd suggest this:
26 function StyleToStr(Style: TFontStyles): string;
27 const
28 Chars: array[Boolean] of Char = ('F', 'T');
29 begin
30 SetLength(Result, 4);
31 Result[1] := Chars[fsBold in Style];
32 Result[2] := Chars[fsItalic in Style];
33 Result[3] := Chars[fsUnderline in Style];
34 Result[4] := Chars[fsStrikeOut in Style];
35 end;
Solve 3:
A more algorithmic approach:
36 function FontStylesToStr(Style: TFontStyles): string;
37 var
38 I: TFontStyle;
39 begin
40 SetLength(Result, High(TFontStyle) + 1);
41 for I := Low(TFontStyle) to High(TFontStyle) do
42 if I in Style then
43 Result[Ord(I) + 1] := 'F'
44 else
45 Result[Ord(I) + 1] := 'T';
46 end;
47
48 function StrToFontStyles(Str: string): TFontStyles;
49 var
50 I: TFontStyle;
51 begin
52 Result := [];
53 for I := Low(TFontStyle) to High(TFontStyle) do
54 if Str[Ord(I) + 1] = 'T' then
55 Include(Result, I);
56 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.
f
57 unction FontStylesToInt(Styles: TFontStyles): Integer;
58 begin
59 Result := byte(Styles)
60 end;
61
62 function IntToFontStyles(Value: integer): TFontStyles;
63 begin
64 Result := TFontStyles(byte(Value))
65 end;
If you are a purist, replace 'integer's with 'byte's
|