在.net cf(compact framework)的環境下面,label的背景沒有辦法設定為透明的,所以如果Form設定了底圖,那麼擺個Label上去就會看到白白的一塊東西在那邊,這該怎麼辦呢?
在.net cf(compact framework)的環境下面,label的背景沒有辦法設定為透明的,所以如果Form設定了底圖,那麼擺個Label上去就會看到白白的一塊東西在那邊,這該怎麼辦呢?
解法可以參考下面這篇
How to get Transparent Label?
他的做法大致上是下面這樣
- 在PictureBox或是Form上先擺上一個"不可見"的Label,也就是visable=false
- 設定好想要的字型跟前景顏色(forecolor)等等
- 利用graphic.drawstring的方式將字畫到PictureBox或是Form上面
那麼為什麼要擺放一個visable=false的Label在上面呢?直接畫不就好了?是的,直接畫當然也是可以,不過這個"不可見"的label可以幫我們"記住"很多事情,例如位置、字型、顏色等等,所以會比較方便。
下面是參考的程式碼(修改自連結中的範例程式)
Dim targetOffset As Point
Dim drawBounds As Rectangle
Dim sizeTmp As SizeF
Dim intleft As Integer
Private Sub DrawLabel(ByRef labSource As Label, ByRef picTarget As Form, ByRef grx As Graphics)
targetOffset = picTarget.Location
drawBounds = labSource.Bounds
drawBounds.X -= picTarget.Location.X
drawBounds.Y -= picTarget.Location.Y
If (labSource.TextAlign = ContentAlignment.TopLeft) Then
grx.DrawString(labSource.Text, labSource.Font, New SolidBrush(labSource.ForeColor), drawBounds)
ElseIf (labSource.TextAlign = ContentAlignment.TopCenter) Then
sizeTmp = grx.MeasureString(labSource.Text, labSource.Font)
intleft = Me.Width / 2 - CInt(sizeTmp.Width) / 2
intleft -= picTarget.Location.X
Dim rect As Rectangle = New Rectangle(Left, labSource.Top, CInt(sizeTmp.Width), CInt(labSource.Height))
grx.DrawString(labSource.Text, labSource.Font, New SolidBrush(labSource.ForeColor), rect)
ElseIf (labSource.TextAlign = ContentAlignment.TopRight) Then
sizeTmp = grx.MeasureString(labSource.Text, labSource.Font)
intleft = labSource.Width - CInt(sizeTmp.Width) + labSource.Left
left -= picTarget.Location.X
Dim rect As Rectangle = New Rectangle(left, labSource.Top, CInt(sizeTmp.Width), CInt(sizeTmp.Height))
grx.DrawString(labSource.Text, labSource.Font, New SolidBrush(labSource.ForeColor), rect)
End If
End Sub
呼叫的方式
Private Sub frmMain_Paint(ByVal sender As Object, ByVal e As System.Windows.Forms.PaintEventArgs) Handles MyBase.Paint
''刷新文字說明
DrawLabel(labMsg, Me, e.Graphics)
End Sub