VB.NET绘制圆形时如何隐藏背景矩形?
VB.NET绘制圆形消除背景矩形框的解决办法
问题原因
- 你误用了
Pens.Red作为FillEllipse的参数——FillEllipse方法需要传入**Brush(画刷)**来填充图形,而Pen是用于绘制线条的,这会导致填充逻辑异常。 - 控件默认会自动绘制矩形背景,这就是你看到的多余矩形框的来源。
修正后的代码
Protected Overrides Sub OnPaint(ByVal e As System.Windows.Forms.PaintEventArgs) ' 跳过默认背景绘制,避免出现矩形底色 MyBase.OnPaintBackground(e) Dim G As Graphics = e.Graphics G.SmoothingMode = SmoothingMode.AntiAlias ' 使用SolidBrush填充圆形,并用Using语句自动释放资源 Using redBrush As New SolidBrush(Color.Red) G.FillEllipse(redBrush, 2, 2, Width - 4, Height - 4) End Using End Sub
额外优化建议
- 如果是自定义控件,可在构造函数中添加以下代码,开启透明背景支持:
Public Sub New() InitializeComponent() SetStyle(ControlStyles.SupportsTransparentBackColor, True) BackColor = Color.Transparent End Sub - 始终用
Using语句管理Brush、Pen这类GDI+资源,防止内存泄漏。
内容的提问来源于stack exchange,提问作者ZAK_99
相关产品推荐
相关产品推荐

