GDI+Windows Vista.NET 1.1Visual Studio 2005设计/图形Windows XP.NET 2.0Windows FormsC# 2.0中级开发Visual StudioWindows.NETASP.NETC#
使用 PNG 中的 Alpha 创建魔法卡
尝试使用 PNG 为您的朋友制作一张魔法卡。

带有白色背景的图片。

带有黑色背景的同一张图片。
引言
这是一个有趣的工具。它将帮助您生成一个具有2个图层的PNG文件,不同的图层有不同的文本,因此您可以将您的信息隐藏在图片中,发送给您的朋友并请他或她猜。
背景
这个想法是为了我送给女朋友(现在是我的妻子)的生日贺卡。我想为她DIY一些礼物,但你知道,我是一个IT男,手工制作对我来说很难,所以我想到了设计一张电子贺卡。 当我在Photoshop上工作时,我为黑白背景创建了2个图层,并在上面放了文本。 幸运的是,我发现了一些有趣的效果,最后我创建了一个带有JavaScript效果的网页,用于将背景颜色从白色更改为黑色,并且图像显示不同的文本。
最近,我的妻子让我再次为她的朋友做这件事,所以我终于为这篇文章编写了这个程序。
Using the Code
有一个函数可以生成图像,其余的主要是UI,我不会专注于此。
该函数如下所示
private void GenerateImage()
{
//get the graphics from image, image is created in the constructor
Graphics g = Graphics.FromImage(m_Image);
//if the image is not free, just clean and redraw
g.Clear(Color.Empty);
int area = m_Image.Width * m_Image.Height;
float x = -1;
float y = -1;
int alpha = -1;
int size = -1;
SolidBrush brush = new SolidBrush(this.ForeColor);
PointF position = new PointF(m_Image.Width / 2, m_Image.Height / 2);
Random rand = new Random();
StringFormat format = new StringFormat();
format.Alignment = StringAlignment.Near;
format.LineAlignment = StringAlignment.Near;
//set the back text color as white
brush.Color = Color.FromArgb(150, Color.White);
g.DrawString(m_BackText, this.Font, brush, position, format);
//draw some star at the background
for (int i = 0; i < area * BACK_STAR_AREA; i++)
{
x = rand.Next(m_Image.Width);
y = rand.Next(m_Image.Height);
alpha = rand.Next(MIN_STAR_ALPHA, MAX_STAR_ALPHA);
size = rand.Next(MIN_STAR_SIZE, MAX_STAR_SIZE);
brush.Color = Color.FromArgb(alpha, Color.LightYellow);
g.FillEllipse(brush, x - size / 2, y - size / 2, size, size);
}
//set the front text as black
brush.Color = Color.FromArgb(180, Color.Black);
g.DrawString(m_FrontText, this.Font, brush, position, format);
//draw some star at the background
for (int i = 0; i < area * FRONT_STAR_AREA; i++)
{
x = rand.Next(m_Image.Width);
y = rand.Next(m_Image.Height);
alpha = rand.Next(MIN_STAR_ALPHA, MAX_STAR_ALPHA);
size = rand.Next(MIN_STAR_SIZE, MAX_STAR_SIZE);
brush.Color =Color.FromArgb(alpha, Color.Black);
g.FillEllipse(brush, x - size / 2, y - size / 2, size, size);
}
//dispose and cleanup
brush.Dispose();
}
关注点
32位alpha图像非常有趣,为了更好地理解您可以尝试一下。一个具有动态效果的静态图像变成了一个不同的图像。现在您不需要准备N个图像和JavaScript效果来更改图像。只需更改背景即可获得不同的视觉效果。现在就动手,给你的朋友一个惊喜吧。
Web浏览器
支持32位PNG的Web浏览器:Internet Explorer 7、Firefox、Safari。
Internet Explorer 6或更早版本不受支持 - 用户将看到背景颜色正在变化,但图像保持不变。
历史
- 2007年10月12日:文章创建