摘要:为偶的NotesManager小程序写了一个带滚动条的Label控件,效果看起来象下面这样:
这个控件的实现思路说起来很简单,就是使用的一般Windows桌面程序中的窗口(Window)和视口(View)的概念。
考虑到Label本身不需要支持编辑的功能,出于效率的考虑,我在ScrollLabel控件中用一个Bitmap对象来保存Window的所有内容。在OnPaint中,如果发现Bitmap对象是空值(通常是第一次Paint),则根据当前Text的内容判断是否需要显示ScrollBar,并创建Bitmap对象,然后根据View的位置来显示应当显示在界面上的内容。以后每次Paint的时候,都只是根据滚动条的位置来计算View的位置,然后显示相应的Bitmap上的内容即可。当Text或者Font改变时,将原有的Bitmap销毁重新计算即可。整个OnPaint方法看起来象下面这样:
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint (e);
if(bmpWindow == null)
{
Rectangle drawRect;
// Calculate the height of the window
SizeF size = e.Graphics.MeasureString(this.Text, this.Font);
rowHeight = size.Height;
float height = (size.Width / ClientSize.Width + 1) * rowHeight;
// Indicate if the scrollbar need to be shown.
if(height > ClientRectangle.Height)
{
// Recalculate the height of window.
height = (size.Width / (ClientSize.Width - scrollWidth)) * rowHeight + ClientSize.Height / 2;
// Show scrollbar
vs.Bounds = new Rectangle(this.ClientSize.Width - scrollWidth, 0,
scrollWidth, ClientSize.Height);
vs.LargeChange = (int)(ClientSize.Height / rowHeight);
vs.Maximum =......[
阅读全文]