圆角矩形不准确 [英] Rounded Rectangle Not Accurate
问题描述
我发现的使用 GDI+ 绘制圆角矩形的每个示例代码都是这样的(从 BobPowell.net 中提取并稍作修改):
Every sample code I've ever found for drawing rounded rectangles using GDI+ goes something like this (lifted and slightly modified from BobPowell.net):
Private Sub Panel1_Paint(ByVal sender As Object, ByVal e As PaintEventArgs) Handles Panel1.Paint
e.Graphics.Clear(SystemColors.Window)
e.Graphics.SmoothingMode = SmoothingMode.None
Call DrawRoundRect(e.Graphics, Pens.Red, 10, 10, 48, 24, 6)
End Sub
Public Sub DrawRoundRect(ByVal g As Graphics, ByVal p As Pen, ByVal x As Single, ByVal y As Single, ByVal width As Single, ByVal height As Single, ByVal radius As Single)
Using gp As New GraphicsPath()
gp.StartFigure()
gp.AddArc(x + width - radius, y, radius * 2, radius * 2, 270, 90)
gp.AddArc(x + width - radius, y + height - radius, radius * 2, radius * 2, 0, 90)
gp.AddArc(x, y + height - radius, radius * 2, radius * 2, 90, 90)
gp.AddArc(x, y, radius * 2, radius * 2, 180, 90)
gp.CloseFigure()
g.DrawPath(p, gp)
End Using
End Sub
这会生成一个圆角矩形,其中只有左上角是准确的.
This produces a rounded rectangle where only the top left corner is accurate.
AntiAliasing 必须关闭,因为它正在通过远程桌面连接,我不能依赖它可用.此外,我正在寻找一个清晰的圆角矩形.
AntiAliasing has to be turned off because it is going through a remote desktop connection, and I can't depend on it being available. Besides, I am looking for a crisp rounded rectangle.
我尝试过调整其他角的大小并更改笔对齐方式,但似乎无法生成简单、准确的圆角矩形.
I've tried resizing the other corners and changing the pen alignments, but nothing seems to produce a simple, accurate rounded rectangle.
有没有办法在旧的 Winforms 中绘制比这更好的圆角矩形?
Is there a way to draw a better rounded rectangle than this in good old winforms?
推荐答案
我发现最好的解决方案是老式 Windows API:
I have found the best solution to be just old-school Windows API:
Private Sub DrawRoundRect(ByVal g As Graphics, ByVal r As Rectangle)
Dim hDC As IntPtr = g.GetHdc
Dim hPen As IntPtr = CreatePen(PS_SOLID, 0, ColorTranslator.ToWin32(Color.Red))
Dim hOldPen As IntPtr = SelectObject(hDC, hPen)
SelectObject(hDC, GetStockObject(NULL_BRUSH))
RoundRect(hDC, r.Left, r.Top, r.Right - 1, r.Bottom - 1, 12, 12)
SelectObject(hDC, hOldPen)
DeleteObject(hPen)
g.ReleaseHdc(hDC)
End Sub
这产生了我一直在寻找的对称圆角矩形:
This produces the symmetrical rounded rectangle I've been looking for:
这篇关于圆角矩形不准确的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!