参考书目:C#6.0学习笔记——从第一行C#代码到第一个项目设计(作者周家安)P328
学习内容:自行绘制列表控件的项,在listbox控件中显示系统字体
第一步:建立界面如下
仅包含一个listBox框,将其Dock属性设置为Fill,DrawMode属性设置为OwnerDrawVariable。
第二步,为列表框添加MeasureItem和DrawItem事件。
第三步,在Form的构造函数中加入读入系统字体的代码
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Example11_14
{
public partial class Form1 : Form
{
/// <summary>
/// 要绘制的文本的字体大小
/// </summary>
const float FONT_SIZE = 16f;
public Form1()
{
InitializeComponent();
this.Load += (s, e) =>
{
// 向ListBox添加字体的名字
foreach (FontFamily family in FontFamily.Families)
{
listBox1.Items.Add(family.Name);
}
};
}
private void listBox1_MeasureItem(object sender, MeasureItemEventArgs e)
{
//取出项中的文本
if(e.Index <0 )
{
return;
}
string itemText = (sender as ListBox).Items[e.Index] as string;
//创建相应的字体
using (Font font = new Font(itemText, FONT_SIZE))
{
//计算待绘制文本的大小(宽度和高度)
SizeF size = e.Graphics.MeasureString(itemText, font);
//设置项的高度
e.ItemHeight = Convert.ToInt32(size.Height);
}
}
private void listBox1_DrawItem(object sender, DrawItemEventArgs e)
{
//取出文本
if (e.Index <0)
{
return;
}
string itemText = (sender as ListBox).Items[e.Index] as string;
//创建用于绘制文本的字体对象
using (Font font = new Font(itemText, FONT_SIZE))
{
//创建用于设置文本格式的对象
StringFormat sf = new StringFormat();
//文本在水平方向上对齐
sf.Alignment = StringAlignment.Near;
//文本在垂直方向上对齐
sf.Alignment = StringAlignment.Center;
//绘制默认背景
e.DrawBackground();
//绘制文本
if ((e.State & DrawItemState.Selected) == DrawItemState.Selected)
{ //&表示与运算,检测某个经组合后的枚举值是否包含某个值
//当前项被选中
e.Graphics.DrawString(itemText, font, SystemBrushes.HighlightText,
e.Bounds, sf);
}
else
{
//当前项未选中
e.Graphics.DrawString(itemText, font, SystemBrushes.ControlText,
e.Bounds, sf);
}
//释放资源
sf.Dispose();
}
}
}
}
运行结果如下:
问题:感觉读入的字体数量不足,为什么呢?