版权声明:本文为博主原创文章,转载请在显著位置标明本文出处以及作者网名,未经作者允许不得用于商业目的。
下载相关代码:【免费】《自己做个国庆75周年头像生成器》代码资源-CSDN文库
又是一年国庆节,今年使用国旗做头像的朋友不少,律师也说了,不违法。
所以,做这个程序也没关系吧。
程序设计界面
准备四张透明png图片到程序目录下的Img目录,分别用1-4.png命名。
主要代码就写在下面了:
Public Class Form1
Dim baseImg As Bitmap
Dim backimg As Bitmap
Dim g As Graphics
Dim blChooseImg As Boolean
Private Sub btnChoosePic_Click(sender As Object, e As EventArgs) Handles btnChoosePic.Click
Dim picname As String
If ofdPic.ShowDialog = DialogResult.Cancel Then
Exit Sub
End If
picname = ofdPic.FileName
Try
backimg = New Bitmap(picname)
blChooseImg = True
Call drawImg(cbMask.SelectedIndex)
Catch ex As Exception
backimg = Nothing
End Try
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
blChooseImg = False
baseImg = New Bitmap(pbCombine.Width, pbCombine.Height)
g = Graphics.FromImage(baseImg)
cbMask.SelectedIndex = 0
AddHandler cbMask.SelectedIndexChanged, AddressOf cbMaskSelectedIndexChanged
End Sub
Private Sub cbMaskSelectedIndexChanged(sender As Object, e As EventArgs)
Call drawImg(cbMask.SelectedIndex)
End Sub
Private Sub drawImg(ByVal maskid As Integer)
If blChooseImg = False Then Exit Sub
g.DrawImage(backimg, New Rectangle(0, 0, pbCombine.Width, pbCombine.Height), New Rectangle(0, 0, backimg.Width, backimg.Height), GraphicsUnit.Pixel)
Dim maskName As String
maskName = Application.StartupPath & "\img\" & (maskid + 1).ToString & ".png"
Dim maskImg As New Bitmap(maskName)
g.DrawImage(maskImg, New Rectangle(0, 0, pbCombine.Width, pbCombine.Height), New Rectangle(0, 0, maskImg.Width, maskImg.Height), GraphicsUnit.Pixel)
pbCombine.Image = baseImg
End Sub
Private Sub pbCombine_MouseDown(sender As Object, e As MouseEventArgs) Handles pbCombine.MouseDown
If e.Button = MouseButtons.Right Then
If blChooseImg = True Then
cmsSave.Show(sender, e.Location)
End If
End If
End Sub
Private Sub tsmSaveImg_Click(sender As Object, e As EventArgs) Handles tsmSaveImg.Click
Dim savePath As String
If sfdPic.ShowDialog = DialogResult.Cancel Then
Exit Sub
End If
savePath = sfdPic.FileName
Try
baseImg.Save(savePath)
MessageBox.Show("保存完毕")
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
Private Sub Form1_FormClosing(sender As Object, e As FormClosingEventArgs) Handles Me.FormClosing
g.Dispose()
baseImg.Dispose()
End Sub
End Class
代码太简单,不一一讲解了。
注意一个地方,窗体载入的时候为什么要:
AddHandler cbMask.SelectedIndexChanged, AddressOf cbMaskSelectedIndexChanged
而不是直接使用 cbMask.SelectedIndexChanged 这个事件呢?
Private Sub cbMask_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cbMask.SelectedIndexChanged
End Sub
请读者自己想一想。
运行时是这样滴:
简简单单的代码,我们不仅可以给自己做,也可以给朋友做头像了。
由于.net平台下C#和vb.NET很相似,本文也可以为C#爱好者提供参考。
学习更多vb.net知识,请参看vb.net 教程 目录