前言
眼瞅着又到了一年一度的国庆节,也到了一年一次的换头像时刻。忘记了从哪一年开始的吧,流行起来了头像+国旗的玩法【爱我中华】,当然前一段时间还有+口罩头像,不过现在疫情已过......
本文使用C#代码来实现生成国旗头像,代码很简单,效果很不错。
开发环境:.NET Framework版本:4.8
开发工具:Visual Studio 2022
实现步骤
首先去找一些头像国旗的素材,至于怎么找?嘿嘿,懂得都懂
放一个选择头像的按钮,选择后显示到页面
private void btn_select_Click(object sender, EventArgs e)
{
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.Filter = "头像图片|*.png;*.jpg";
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
pic_old.Image = Image.FromFile(openFileDialog.FileName);
}
}
使用GDI+进行绘制,将两张图片合并到一起(由于事先得到的素材已经有透明背景填充,所以无需过多处理)
Image head = (Image)pic_old.Image.Clone();
Image template = Image.FromFile(files[index].FullName);
Graphics graphics = Graphics.FromImage(head);
if (files[index].Name.StartsWith("all_"))
{
graphics.DrawImage(template, 0, 0, head.Width, head.Height);
}
else if (files[index].Name.StartsWith("right_"))
{
int x = head.Width / 4 * 3;
int y = head.Height / 4 * 3;
int w = head.Width / 4;
int h = head.Height / 4;
//Color color = Color.FromArgb(200, 255, 255, 255);
//Brush brush = new SolidBrush(color);
//graphics.FillPie(brush, x, y, w, h, 0, 360);
//graphics.FillRectangle(brush, x + w / 2, y + h / 2, w / 2, h / 2);
graphics.DrawImage(template, x, y, w, h);
}
else if (files[index].Name.StartsWith("left_"))
{
int y = head.Height - template.Height;
if (y < 0) y = 0;
graphics.DrawImage(template, 0, y, head.Width, head.Height);
}
pic_new.Image = head;
保存图片代码
private void btn_save_Click(object sender, EventArgs e)
{
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.Filter = "图片文件|*.png";
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
pic_new.Image.Save(saveFileDialog.FileName, ImageFormat.Png);
MessageBox.Show("保存成功");
}
}
实现效果
☛☛☛点击此处下载源码☚☚☚
联系客服