前言
随着一年一度的国庆假期越来越近,身边的国庆氛围也越来越重,很多人也开始换上了渐变国旗头像,提前为祖国母亲庆生。那每年都很火的渐变国旗头像要如何制作呢?其实一点也不难!接下来就分享一种渐变国旗头像生成方法。
制作原理
上传原始微信或其他头像,将头像的Image对象用Graphics创建返回GDI+对象,然后用GDI+对象在原始头像指定位置进行追加绘制指定大小的图像渲染显示。
项目架构设计
演示项目为Winform窗体应用程序,项目具体信息如下:
项目框架:
.NET Framework 4.8
项目架构和窗体设计:

五星红旗模板准备:

代码实现
选择头像代码:
- /// <summary>
- /// 选择头像
- /// </summary>
- /// <param name="sender"></param>
- /// <param name="e"></param>
- private void btn_select_Click(object sender, EventArgs e)
- {
- OpenFileDialog openFileDialog = new OpenFileDialog();
- openFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);//初始路径为桌面
- openFileDialog.Filter = "头像图片|*.png;*.jpg";
- if (openFileDialog.ShowDialog() == DialogResult.OK)
- {
- pic_old.Image = Image.FromFile(openFileDialog.FileName);
- }
- }
-
复制代码 生成和切换模板代码
- /// <summary>
- /// 生成或切换模板事件
- /// </summary>
- /// <param name="sender"></param>
- /// <param name="e"></param>
- private void btn_change_Click(object sender, EventArgs e)
- {
- GenerateOrChangeTemplate();
- }
-
- /// <summary>
- /// 生成头像或切换模板生成头像
- /// </summary>
- private void GenerateOrChangeTemplate()
- {
- try
- {
- if (templateFileInfos.Length == 0)
- {
- MessageBox.Show("红旗模板集为空,请添加", "提示", MessageBoxButtons.OK);
- return;
- }
- if (index >= templateFileInfos.Length)
- {
- index = 0;
- }
- Image head = (Image)pic_old.Image.Clone();
- Image template = Image.FromFile(templateFileInfos[index].FullName);
- Graphics graphics = Graphics.FromImage(head);
- if (templateFileInfos[index].Name.StartsWith("all_"))
- {
- graphics.DrawImage(template, 0, 0, head.Width, head.Height);
- }
- else if (templateFileInfos[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;
- graphics.DrawImage(template, x, y, w, h);
- }
- else if (templateFileInfos[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;
- index++;
- }
- catch (Exception ex)
- {
- MessageBox.Show("出错了:"+ ex.Message,"警号",MessageBoxButtons.OK);
- }
- }
复制代码 保存代码
- /// <summary>
- /// 保存重新绘制的图片
- /// </summary>
- /// <param name="sender"></param>
- /// <param name="e"></param>
- 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("保存成功");
- }
- }
复制代码 效果演示

源码工具获取
关注公众号,后台回复关键字:五星红旗头像
友情提示:仅供学习研究使用,切勿非法使用!
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作! |