如何在PictureBox上透明的显示文字(利用控件技术)

2009年3月13日星期五

如何在PictureBox上透明的显示文字(利用控件技术)

关键点有2点:

1、将此控件的背景颜色设为透明色,

2、将此控件和父控件关联,即和PictureBox控件相关联。

范例代码如下:(关键性代码已用黑体字表示

范例功能:当鼠标在图片上按下时,显示“你好”,当鼠标抬起后,文字自动消失。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace CCDTest
{
public partial class Form1 : Form
{
string filename;
Label lblResult;
public Form1()
{
InitializeComponent();
filename = Application.StartupPath + "\\cc1.bmp";
lblResult = new Label();
lblResult.Location = new Point(0,0);
lblResult.Parent = pbCCD;
lblResult.BackColor = Color.Transparent;
lblResult.Text = "你好!";
lblResult.Visible = false;
}

private void Form1_Load(object sender, EventArgs e)
{
pbCCD.Load(filename);
}

private void pbCCD_MouseDown(object sender, MouseEventArgs e)
{
lblResult.Visible = true;

lblResult.Location = e.Location;
}

private void pbCCD_MouseUp(object sender, MouseEventArgs e)
{
lblResult.Visible = false;
}
}
}





利用c#的GDI+技术,PictureBox.CreateGraphics()绘图,利用g.DrawString写文字。

利用this.Invalidate()刷新Form窗体,或者利用PictureBox.Invalidate()刷新PictureBox.。

范例代码如下:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace CCDTest
{
public partial class Form1 : Form
{
string filename;
//Label lblResult;
public Form1()
{
InitializeComponent();
filename = Application.StartupPath + "\\cc1.bmp";
}

private void Form1_Load(object sender, EventArgs e)
{
pbCCD.Load(filename);
}

private void pbCCD_MouseDown(object sender, MouseEventArgs e)
{
PointF pf = e.Location;

using (Graphics g = pbCCD.CreateGraphics())
{
Console.WriteLine("Beg MyDraw....");
Font f = new Font("Arial", 12);
g.DrawString("Hello!", f, Brushes.Violet, pf);
Console.WriteLine("End MyDraw.....");
}
}

private void pbCCD_MouseUp(object sender, MouseEventArgs e)
{
pbCCD.Invalidate();
}
}
}

0 评论:

发表评论