你可以做一个自定义控件, 把控件的形状挖成文字的形状. 这样就作到了真正的透明.using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;namespace TransparenceFont
{
public partial class RealTransparentLabel : UserControl
{
private string text; public string _Text
{
get { return text; }
set
{
text = value;
OnTextChanged();
}
} public RealTransparentLabel()
{
InitializeComponent();
this._Text = this.Name;
} private void OnTextChanged()
{
if (text == null || text == "")
{
this.Width = 1;
return;
}
//计算文字区域大小
Bitmap tmp = new Bitmap(1, 1);
Graphics measure = Graphics.FromImage(tmp);
SizeF sz = measure.MeasureString(text, Font);
tmp.Dispose();
measure.Dispose();
Size size = new Size((int)sz.Width, (int)sz.Height);
this.Size = size; //绘制文字
Bitmap img = new Bitmap(size.Width, size.Height);
Graphics gph = Graphics.FromImage(img);
gph.DrawString(text, Font, new SolidBrush(ForeColor), 0, 0);
gph.Dispose();
this.BackgroundImage = img; //除去控件多余区域
Color transp = img.GetPixel(0,0);
Region reg = new Region();
reg.MakeEmpty();
for (int i = 0; i < size.Width; i++)
{
for (int j = 0; j < size.Height; j++)
{
if (img.GetPixel(i, j) != transp)
{
reg.Union(new Rectangle(i, j, 1, 1));
}
}
}
this.Region = reg;
}
}
}
效果如图下面的对比是普通Label控件用透明色做背景, 其背景只是窗体的背景.
而RealTransparentLabel完全透明了.
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;namespace TransparenceFont
{
public partial class RealTransparentLabel : UserControl
{
private string text; public string _Text
{
get { return text; }
set
{
text = value;
OnTextChanged();
}
} public RealTransparentLabel()
{
InitializeComponent();
this._Text = this.Name;
} private void OnTextChanged()
{
if (text == null || text == "")
{
this.Width = 1;
return;
}
//计算文字区域大小
Bitmap tmp = new Bitmap(1, 1);
Graphics measure = Graphics.FromImage(tmp);
SizeF sz = measure.MeasureString(text, Font);
tmp.Dispose();
measure.Dispose();
Size size = new Size((int)sz.Width, (int)sz.Height);
this.Size = size; //绘制文字
Bitmap img = new Bitmap(size.Width, size.Height);
Graphics gph = Graphics.FromImage(img);
gph.DrawString(text, Font, new SolidBrush(ForeColor), 0, 0);
gph.Dispose();
this.BackgroundImage = img; //除去控件多余区域
Color transp = img.GetPixel(0,0);
Region reg = new Region();
reg.MakeEmpty();
for (int i = 0; i < size.Width; i++)
{
for (int j = 0; j < size.Height; j++)
{
if (img.GetPixel(i, j) != transp)
{
reg.Union(new Rectangle(i, j, 1, 1));
}
}
}
this.Region = reg;
}
}
}
效果如图下面的对比是普通Label控件用透明色做背景, 其背景只是窗体的背景.
而RealTransparentLabel完全透明了.
解决方案 »
免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货