本文的開發環境
作業系統:xp
程式開發環境vss2008+windowMobile6.1Professional
概述:
在WindowMobile開發過程中,尤其是對介面要求高的UI設計過程中,我們需要實現帶有自訂背景圖片的標籤。
面向這樣的需求,我們通常的想法是繼承lable控制項,並Override控制項的OnPaint方法。然而怪異的現象是繼承的控制項用盡各種方法就是不處罰OnPaint方法。在網路上好多人也碰到這樣的問題。下面是基於自訂控制項的方式進行實現思路。
自訂方式實現可定義背景圖片的lable控制項。
解決的思路為:
定義一個控制項繼承與Control,
Override OnPaint方法。
在OnPaint方法做以下幾件事
l 首先清空當前背景
l 繪製背景
l 顯示當前的標籤文本,注意在繪製文本時,文本的背景用Color.Transparent,
舉例:
下面是實際項目中的一個應用
顯示一個當前遊戲玩家血的控制項,背景為當前的血量圖片,顯示的文本為當前血值
具體的效果如下:
具體代碼如下:
代碼
/// <summary>
/// 繼承並重新設定背景
/// 按照當前血的比值設定
/// </summary>
/// <param name="e"></param>
protected override void OnPaintBackground(PaintEventArgs e)
{
base.OnPaintBackground(e);
//step One 對背景進行清除
e.Graphics.Clear(Color.White);
//Step Two 對當前背景 進行重新繪畫
int length = (BloodNum / MaxBloodNum) * this.Width;
using (SolidBrush brush = new SolidBrush(this.BackColor))
{
e.Graphics.FillRectangle(brush, new Rectangle(0, 0, length, this.Height));
}
//Step Three 對當前未填充的部分進行填充
using (SolidBrush brush = new SolidBrush(Color.DarkOliveGreen))
{
e.Graphics.FillRectangle(brush, new Rectangle(length, 0, (this.Width - length), this.Height));
}
//Step Four 顯示當前血的值
using (Pen pen = new Pen(this.ForeColor))
{
using (SolidBrush brush = new SolidBrush(Color.Transparent))
{
//設定文本地區
e.Graphics.DrawString(this.BloodNum.ToString(), this.Font, brush, ((this.Width / 2)-5), 0);
}
}
}