之前的教程中曾使用Graphics.DrawString绘制文字,这个示例来说明如何绘制一个透明的文字水印。
设计界面:
其中,一个HScrollBar控件用于控制透明度,取值范围为0-255
当调整HScrollBar时,在label上显示实际的值:
Private Sub HScrollBar1_Scroll(sender As Object,e As ScrollEventArgs) Handles HScrollBar1.Scroll Label2.Text = HScrollBar1.Value.ToString End Sub
Private Sub Button1_Click(sender As Object,e As EventArgs) Handles Button1.Click Dim logoOpacity As Integer = HScrollBar1.Value Dim logoText As String = TextBox1.Text Dim logoFont As New Font(New FontFamily("隶书"),40,FontStyle.Bold) Dim logoBrush As New SolidBrush(Color.FromArgb(logoOpacity,255,255)) Dim logoLeft As Integer = 10 Dim logoTop As Integer = 10 Dim imgDest As Bitmap = PictureBox1.Image.Clone Dim g As Graphics = Graphics.FromImage(imgDest) g.DrawString(logoText,logoFont,logoBrush,logoLeft,logoTop) g.Dispose() PictureBox3.Image = imgDest End Sub
运行效果:
下面对代码稍作分析:
1、Dim imgDest As Bitmap = PictureBox1.Image.Clone
为什么要用Clone,大家可以修改为 Dim imgDest As Bitmap = PictureBox1.Image ,当绘制水印完毕后,最小化程序窗口,再恢复窗口看一下。
2、透明度是由drawstring中颜色参数来控制的: