Mega Code Archive

 
Categories / Delphi / Examples
 

Convert font attributes to a string and vise versa

Sometimes it's necessary to represent attributes of certain objects as strings. For example, if your program allows the user to change fonts and you want to save these customized font attributes in the registry, you might want to save these attributes as strings. Following two functions will let you convert a font object's attributes into a string and then convert formatted string back into font attributes: const csfsBold = '|Bold'; csfsItalic = '|Italic'; csfsUnderline = '|Underline'; csfsStrikeout = '|Strikeout'; // // Expected format: // "Arial", 9, [Bold], [clRed] // procedure StringToFont( sFont : string; Font : TFont ); var p : integer; sStyle : string; begin with Font do begin // get font name p := Pos( ',', sFont ); Name := Copy( sFont, 2, p-3 ); Delete( sFont, 1, p ); // get font size p := Pos( ',', sFont ); Size := StrToInt( Copy( sFont, 2, p-2 ) ); Delete( sFont, 1, p ); // get font style p := Pos( ',', sFont ); sStyle := '|' + Copy( sFont, 3, p-4 ); Delete( sFont, 1, p ); // get font color Color := StringToColor( Copy( sFont, 3, Length( sFont ) - 3 ) ); // convert str font style to // font style Style := []; if( Pos( csfsBold, sStyle ) > 0 )then Style := Style + [ fsBold ]; if( Pos( csfsItalic, sStyle ) > 0 )then Style := Style + [ fsItalic ]; if( Pos( csfsUnderline, sStyle ) > 0 )then Style := Style + [ fsUnderline ]; if( Pos( csfsStrikeout, sStyle ) > 0 )then Style := Style + [ fsStrikeout ]; end; end; // // Output format: // "Aril", 9, [Bold|Italic], [clAqua] // function FontToString( Font : TFont ) : string; var sStyle : string; begin with Font do begin // convert font style to string sStyle := ''; if( fsBold in Style )then sStyle := sStyle + csfsBold; if( fsItalic in Style )then sStyle := sStyle + csfsItalic; if( fsUnderline in Style )then sStyle := sStyle + csfsUnderline; if( fsStrikeout in Style )then sStyle := sStyle + csfsStrikeout; if( ( Length( sStyle ) > 0 ) and ( '|' = sStyle[ 1 ] ) )then begin sStyle := Copy( sStyle, 2, Length( sStyle ) - 1 ); end; Result := Format( '"%s", %d, [%s], [%s]', [ Name, Size, sStyle, ColorToString( Color ) ] ); end; end;