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