上方廣告

2009年1月11日 星期日

WinForm 背景圖

在winform表單上加上背景圖,並使Label透明,網路上流傳許多像label1.BackColor = System.Drawing.Color.Transparent這樣的語法,其實是不正確的,這樣只是會讓label標籤的背景跟winform表單 一樣的顏色。

在winform繪製背景圖主要有下列三種方式
方法一:此種方式主要是將圖片放在PictureBox上,並將其他的控件的父親控件改成PictureBox,此方法只有winform有效,智慧型裝置無效。
pictureBox1.Image = Resource1.MainMenu;
pictureBox1.SendToBack();
label1.BackColor = Color.Transparent;
label1.Parent = pictureBox1;
label1.BringToFront();


方法二:此種方法將圖片再表單初始化的時候從新繪製,我將此方法運用在智慧型裝置上面。
Bitmap backImageMainMenu;
Graphics gxBuffer;
Bitmap offBitmap;
string path;

private void Form1_Load(object sender, EventArgs e)
{
    label1.BackColor = System.Drawing.Color.Transparent;
    offBitmap = new Bitmap(this.Width, this.Height);
    gxBuffer = Graphics.FromImage(offBitmap);
    path = System.IO.Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase);
    backImageMainMenu = new Bitmap(Resource1.MainMenu);
}

protected override void OnPaint(PaintEventArgs e)
{
    gxBuffer.Clear(this.BackColor);
    //Draw background first
    gxBuffer.DrawImage(backImageMainMenu, 0, 0);

    e.Graphics.DrawImage(offBitmap, 0, 0);

    foreach (Control C in this.Controls)
    {
        if (C is Label)
        {
            Label L = (Label)C;
            L.Visible = false;

            e.Graphics.DrawString(L.Text, L.Font, new SolidBrush(L.ForeColor), L.Left, L.Top);
        }
        if (C is PictureBox)
        {
            PictureBox L = (PictureBox)C;
            L.Visible = false;
            e.Graphics.DrawImage(Resource1.Calculator_46x46_pressed, pictureBox1.Location.X, pictureBox1.Location.Y);
        }
    }
}


方法三:此種方法類似第一種方法將背景圖放在PictureBox內,並在從新繪製時改變其他控制項的背景。
private void Form2_Load(object sender, EventArgs e)
{
    pictureBox1.Image = Resource1.MainMenu;
    pictureBox2.Image = Resource1.Calculator_46x46_pressed;
}

private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
    foreach (Control C in this.Controls)
    {

        if (C is Label)
        {

            Label L = (Label)C;

            L.Visible = false;

            e.Graphics.DrawString(L.Text, L.Font, new

            SolidBrush(L.ForeColor), L.Left - pictureBox1.Left, L.Top - pictureBox1.Top);

        }
        if (C is PictureBox)
        {
            PictureBox L = (PictureBox)C;
            if (L.Name != "pictureBox1")
            {
                L.Visible = false;
                e.Graphics.DrawImage(Resource1.Calculator_46x46_pressed, pictureBox2.Location.X, pictureBox2.Location.Y);
                //e.Graphics.DrawString(L.Text, L.Font, new

                //SolidBrush(L.ForeColor), L.Left - pictureBox1.Left, L.Top - pictureBox1.Top);
            }
        }

    }
}