本文將建立一個winform項目中運用graphics繪制跑馬燈效果的簡單實例,以下是詳細步驟:
新建一個winform項目WinPicRoll,本例采用框架.net 2.0,如果采用.net 4.0某些屬性的使用會略有不同,並放入一些演示用圖片,滾動用圖片采用png格式,一張背景圖片采用jpg格式,設置所有圖片素材的屬性為"如果較新則復制",這樣就可以在程序中使用相對路徑來獲取圖片。
在Form1中,添加布局代碼,本例采用一個picturebox用來演示。
public Form1()
{
InitializeComponent();
this.FormLayout();
}
PictureBox pb_PicRoll; //顯示區域
/// <summary>
/// 窗體布局
/// </summary>
void FormLayout()
{
this.DoubleBuffered = true;
this.StartPosition = FormStartPosition.CenterScreen;
this.Size = new Size(300, 400);
this.BackColor = Color.LightBlue;
pb_PicRoll = new PictureBox();
pb_PicRoll.Location = new Point(50, 50);
pb_PicRoll.Size = new Size(200, 200);
this.Controls.Add(pb_PicRoll);
}
private void Form1_Load(object sender, EventArgs e)
{
this.InitPicRoll();
}
下面完成跑馬燈的初始化方法InitPicRoll,獲取Images文件夾下的所有png圖片作為滾動用,設置滾動的區域為picturebox的顯示區域,為picturebox設置一個畫筆graphics,畫筆可以在指定的區域繪制圖片、文字、線條等等。
List<Image> ls_images = new List<Image>(); //存放圖片組
Timer t_remain = new Timer(); //切換
Timer t_roll = new Timer(); //滾動
int n_index = 0; //滾動索引
int n_height; //滾動高度
int n_width; //滾動寬度
int n_top; //滾動上邊距
Graphics gh_bg; //畫筆
void InitPicRoll()
{
string[] img_files = Directory.GetFiles(string.Format("{0}/Images", Application.StartupPath), "*.png");
foreach (string img_path in img_files)
{
ls_images.Add(Image.FromFile(img_path));
}
n_height = pb_PicRoll.Height;
n_width = pb_PicRoll.Width;
gh_bg = pb_PicRoll.CreateGraphics();
t_remain.Interval = 5 * 1000;
t_remain.Tick += new EventHandler(t_remain_Tick);
t_roll.Interval = 30;
t_roll.Tick += new EventHandler(t_roll_Tick);
t_remain.Start();
t_roll.Start();
}
在初始化跑馬燈的時候,同時初始化了兩個時鍾,t_remain用來調整滾動的頻率,t_roll用來完成繪圖的工作,代碼如下:
void t_remain_Tick(object sender, EventArgs e)
{
n_index = ++n_index % ls_images.Count;
n_top = 0;
t_roll.Start();
}
void t_roll_Tick(object sender, EventArgs e)
{
n_top -= 5;
if (n_top <= -n_height)
{
t_roll.Stop();
}
Bitmap bt = new Bitmap(n_width, n_height);
Graphics gh = Graphics.FromImage(bt);
for (int i = 0; i < 2; i++)
{
gh.DrawImage(Image.FromFile(string.Format("{0}/Images/bg.jpg", Application.StartupPath)), new Rectangle(new Point(0, n_top + i * n_height), new Size(n_width, n_height)));
gh.DrawImage(ls_images[(n_index + i) % ls_images.Count], new Rectangle(new Point(0, n_top + i * n_height), new Size(n_width, n_height)));
}
gh_bg.DrawImage(bt, new Rectangle(new Point(0, 0), new Size(n_width, n_height)));
gh.Dispose();
bt.Dispose();
}
需要注意的是,繪圖的采用的方式是,先new一個bitmap,然后在bitmap上完成繪制動作,最后將繪制完成的bitmap繪制到演示用的pictruebox區域上,這樣做可以避免直接在最終演示區域進行復雜的繪制動作,能夠有效減少屏幕閃爍的情況。另外繪制的時候,不用頻繁的清除之前的繪圖痕跡,可以如本例中的一樣,先繪制一個jpg的背景圖片,背景不是透明色的圖片可以簡單的覆蓋掉之前殘留的繪圖痕跡,而后繪制上背景為透明png圖片。
重新生成項目,F5運行,效果如下: