【问题标题】:Label text with border带边框的标签文本
【发布时间】:2018-04-05 16:04:12
【问题描述】:

我有一个标签,前景色为白色,文本为“用户名”,表单为天蓝色。我想在标签本身而不是在其中的文本上添加黑色边框。

这可能吗?

 Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        btnLogin.Enabled = False
        centrarVentana(Me)
        lblNombreUsuario.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle
End Sub

代码显然只是为了展示,因为它没有做我想要的。

编辑最终版:非常感谢大家。它终于奏效了!我将代码留在这里,以便每个人都可以重复使用。一旦你理解了它实际上真的很容易。

Imports System.Drawing.Drawing2D

Public Class BorderLabel
    Inherits Label
    Public outline_color As Color = Color.Black
    Public border_thickness As Integer = 5
    Public Sub New()
        MyBase.New

    End Sub


    Protected Overrides Sub OnPaint(ByVal e As PaintEventArgs)
        e.Graphics.FillRectangle(New SolidBrush(BackColor), ClientRectangle)
        Dim gp As GraphicsPath = New GraphicsPath
        Dim outline As Pen = New Pen(Me.outline_color, Me.border_thickness)
        Dim sf As StringFormat = New StringFormat
        Dim foreBrush As Brush = New SolidBrush(ForeColor)
        gp.AddString(Text, Font.FontFamily, CType(Font.Style, Integer), Font.Size, ClientRectangle, sf)
        e.Graphics.ScaleTransform(1.3!, 1.35!)
        e.Graphics.SmoothingMode = SmoothingMode.HighQuality
        e.Graphics.DrawPath(outline, gp)
        e.Graphics.FillPath(foreBrush, gp)
    End Sub
End Class

注意:这个问题与Setting a Font with outline Color in C# 不完全相同,因为我使用的是 Visual Basic,并且必须更改代码才能使其正常工作。

【问题讨论】:

  • @HansPassant 感谢 Pasant。你的链接是我需要的。我正在按照步骤进行操作。而且我可以在工具箱中看到自定义标签,但是当我单击它以将其添加到表单时,它无法说“它无法添加类,因此它将从工具箱中删除”。
  • 您是否尝试先构建您的解决方案 (CTRL + SHIFT + B),然后再添加它?您是否也通过使用 C# DLL 或将代码转换为 VB.NET 来添加它?
  • 很高兴我能帮上忙!您应该将您的解决方案作为答案而不是在您的问题中发布,或者接受副本以关闭问题。

标签: vb.net visual-studio colors label border


【解决方案1】:

看看KeithS answer

您也可以创建自己的标签:

    Public Class CustomLabel
    Inherits Label

    Protected Overrides Sub OnPaint(ByVal e As PaintEventArgs)
        MyBase.OnPaint(e)
        ControlPaint.DrawBorder(e.Graphics, ClientRectangle, Color.Red, 5, ButtonBorderStyle.Solid, Color.Red, 5, ButtonBorderStyle.Solid, Color.Red, 5, ButtonBorderStyle.Solid, Color.Red, 5, ButtonBorderStyle.Solid)
    End Sub
End Class

这就是你如何实现它

Dim newForm As Form = New Form
Dim newLabel As CustomLabel = New CustomLabel
newForm.Controls.Add(newLabel)
newLabel.BackColor = Color.Black
newLabel.Font = New System.Drawing.Font("Microsoft Arial", 18!, FontStyle.Regular, GraphicsUnit.Point, CType(0,Byte))
newLabel.ForeColor = Color.Crimson
newLabel.Text = "Some text on a topmost transparent form window"
newForm.Show
newForm.TopMost = true
newLabel.AutoSize = true
newLabel.Location = New Point(230, 375)

【讨论】:

  • 我可以看出他提出了将一个标签置于另一个之上的想法。看起来真的很讨厌,但它可能对我想要的有用。关于您在此处评论的代码,这只会在标签周围添加一个矩形边框,而不是文本本身的边框。我说的对吗?
  • 您可以通过标签上的标签获得想法。我想我已经实现了你正在寻找的东西。如果我是对的,请告诉我:here
  • 是的,它会起作用,但上述解决方案更好,因为它们不那么丑陋和不可靠。如果我调整窗口大小会发生什么?相对位置是否会保持相同以产生相同的效果?看看我最终使用的解决方案。好多了,谢谢哥们!
  • 是的,我意识到当我在寻找我在图片中显示的解决方案时,您选择了另一种干净且更快的解决方案。但无论如何,我很高兴你找到了它。继续编码!
最近更新 更多