通常在做报表打印的时候,有些字符串会超过单元格,为了能在同一页面中打印出所有列,可能会选择横向打印,或者缩小字体以填满单元格。由于Windows系统采用TrueType字体,在进行变倍时,纵横比保持不变,如果一味地缩小字体,可能会造成字形过小、看不清楚。如果可以创建出纵横比可变的字体,那么就可以满足需求了。
Windows为我们提供了丰富的API函数,调用其中的CreateFont可以创建逻辑字体,过程非常简单,这里我用Delphi进行代码举例:
一、新建一个Application,在Form1上新建3个Label和1个Button。3个Label的基本属性一致,其中AutoSize为False,Caption为”楼竞网站”,Font属性如下图所示:
我故意将Label设置得比较小,以便文字不能全部被显示,如下图所示:
二、为Button1增加Click事件,全部代码如下:
procedure TForm1.Button1Click(Sender: TObject);
var
font1 : HFONT;
font2 : HFONT;
begin
font1 := CreateFont (
Label1.Font.Height, // height of font
Label1.Width div 8, // average character width
0, // angle of escapement
0, // base-line orientation angle
0, // font weight
0, // italic attribute option
0, // underline attribute option
0, // strikeout attribute option
0, // character set identifier
0, // output precision
0, // clipping precision
0, // output quality
0, // pitch and family
Label1.Font.ClassInfo // typeface name(这个参数我不是很确定)
);
font2 := CreateFont (
Label1.Font.Height, // height of font
Label1.Width div 16, // average character width
0, // angle of escapement
0, // base-line orientation angle
0, // font weight
0, // italic attribute option
0, // underline attribute option
0, // strikeout attribute option
0, // character set identifier
0, // output precision
0, // clipping precision
0, // output quality
0, // pitch and family
Label1.Font.ClassInfo // typeface name(这个参数我不是很确定)
);
Label2.Font.Handle := font1;
Label3.Font.Handle := font2;
end;
这里,注意font1和font2创建的区别。
三、运行程序,单击Button1,可以看到创建的逻辑字体产生的压缩效果,如下图所示:
四、如果是在C++ Builder中,请做如下修改:
void __fastcall TForm1::Button1Click(TObject *Sender)
{
HFONT font;
font = CreateFont (
Label1->Font->Height, // height of font
Label1->Width/8, // average character width
0, // angle of escapement
0, // base-line orientation angle
0, // font weight
0, // italic attribute option
0, // underline attribute option
0, // strikeout attribute option
0, // character set identifier
0, // output precision
0, // clipping precision
0, // output quality
0, // pitch and family
(char*)Label1->Font->ClassInfo() // typeface name
);
Label1->Font->Handle = font;
}
很简单的例子,有关CreateFont函数的详细信息,您可以参看MSDN。