您可以使用 FlowlayoutPanel 和新的 Chatbubble 用户控件。
首先,您需要向您的项目添加一个新的用户控件。叫它ChatBubble。
如果您使用 Control 类或 UserControl 类,这基本上取决于您。我在示例中偶然使用了Control,但这并没有太大的区别。
类型在自动创建的.Desiger 中定义。 Visual Studio 的文件。
没有定义控件的一些属性
Public Class ChatBubble
'The "Inherits Control/Usercontrol statement is found in the designer
Public Enum LeftRight
Left = 0
Right = 1
End Enum
Public Property Orientation As LeftRight
Public Property BackBrush As Brush
方向定义聊天气泡是左对齐还是右对齐,Backbrush 是气泡的背景颜色。
构造函数用于设置控件的更多参数
Public Sub New()
InitializeComponent()
SetStyle(ControlStyles.ResizeRedraw, True) 'Redraw the control on resize
SetStyle(ControlStyles.OptimizedDoubleBuffer, True) 'Double buffer the drawing
SetStyle(ControlStyles.AllPaintingInWmPaint, True) 'Used to draw the control yourself
SetStyle(ControlStyles.UserPaint, True) 'Used to draw the control yourself
BackBrush = Brushes.Blue 'Default values
Orientation = LeftRight.Left 'Default values
Me.Padding = New Padding(5) 'Default values
End Sub
默认文本属性用于聊天文本。
现在你实际上需要绘制控件
Protected Overrides Sub OnPaint(ByVal e As System.Windows.Forms.PaintEventArgs)
MyBase.OnPaint(e)
'Smooth the output
e.Graphics.SmoothingMode = Drawing2D.SmoothingMode.AntiAlias
'Measure the size of your content
Dim textSize As SizeF = e.Graphics.MeasureString(Me.Text, Me.Font)
'Ellipse defines the extents of the bubble
Dim Ellipse As Rectangle
'Setup the ellipse depending on the orientation
'Include margins (5 inside, padding of the control outside)
If Orientation = LeftRight.Left Then
Ellipse = New Rectangle(Me.ClientRectangle.Left + Me.Padding.Left, Me.ClientRectangle.Top + Me.Padding.Top, _
textSize.Width + 10, Me.ClientRectangle.Height - Me.Padding.Bottom - Me.Padding.Top)
Else
Ellipse = New Rectangle(Me.ClientRectangle.Right - (textSize.Width + 10) - Me.Padding.Right, Me.ClientRectangle.Top + Me.Padding.Top, _
textSize.Width + 10, Me.ClientRectangle.Height - Me.Padding.Bottom - Me.Padding.Top)
End If
'Define the text's location, center top/bottom
Dim TextLocation As Point = New Point(Ellipse.Left + 5, CInt(Me.ClientSize.Height / 2 - textSize.Height / 2))
'Draw the bubble
e.Graphics.FillEllipse(BackBrush, Ellipse)
'Draw the string
e.Graphics.DrawString(Me.Text, Me.Font, Brushes.White, TextLocation)
End Sub
这是一个非常粗略的例子。您可以根据您的文本自动调整控件大小,包括文本换行,但这基本上可以满足您的需求。
像这样将气泡添加到顶部/底部 Flowlayoutpanel:
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
'flp is the flowlayoutpanel
Static count As Integer = 1
Dim b As New ChatBubble
With b
.Text = "Hello World " & count.ToString
.Orientation = If(count Mod 2 = 0, ChatBubble.LeftRight.Left, ChatBubble.LeftRight.Right)
.Size = New Size(flp.Width, 30)
End With
flp.Controls.Add(b)
count += 1
End Sub
Private Sub flp_Resize(sender As Object, e As EventArgs) Handles flp.Resize
For Each c As Control In flp.Controls
c.Width = flp.Width
Next
End Sub
End Class
样本输出: