[英]How to draw a rounded rectangle with width less than height? C#
我一直在尋找一個已經預制的函數來創建一個圓角矩形,它不會像下面的那樣導致撕裂/毛刺。 感謝@György Kőszeg 。 如果矩形足夠大,這個函數就可以正常工作。 當您開始縮小矩形時,您會遇到如下圖所示的問題。 我正在尋找一個簡單的解決方法。
如果這個問題出現在這個網站上而我錯過了,我很抱歉重新提問。 (我記得曾經在這里或其他網站上問過這個問題,並收到了一個非常有效的答案)這個問題(再次)讓我痛苦了很長一段時間。
public static GraphicsPath RoundedRect(Rectangle bounds, int radius)
{
int diameter = radius * 2;
Size size = new Size(diameter, diameter);
Rectangle arc = new Rectangle(bounds.Location, size);
GraphicsPath path = new GraphicsPath();
if (radius == 0)
{
path.AddRectangle(bounds);
return path;
}
// top left arc
path.AddArc(arc, 180, 90);
// top right arc
arc.X = bounds.Right - diameter;
path.AddArc(arc, 270, 90);
// bottom right arc
arc.Y = bounds.Bottom - diameter;
path.AddArc(arc, 0, 90);
// bottom left arc
arc.X = bounds.Left;
path.AddArc(arc, 90, 90);
path.CloseFigure();
return path;
}
更新:
與此同時,我開始使用下面的代碼,如果寬度小於高度,它只會覆蓋矩形。 這將創建一個完美的圓(圓角矩形可以是沒有毛刺/撕裂的最小的圓)。 對此發表了評論,指出我不應該使用“撕裂”,因為它只是由我理解的數學引起的,但我真的不知道還有什么可以稱呼圖像中的毛刺矩形。
基本上我想要一個橢圓形而不是圓形來正確地反映“Exp”值。
public static GraphicsPath RoundedRect(Rectangle bounds, int radius)
{
int diameter = radius * 2;
Size size = new Size(diameter, diameter);
Rectangle arc = new Rectangle(bounds.Location, size);
GraphicsPath path = new GraphicsPath();
//new code here//
if(bounds.Height >= bounds.Width)
{
bounds.Width = bounds.Height;
}
if (radius >= diameter) {
path.AddRectangle(bounds);
return path;
}
// top left arc
path.AddArc(arc, 180, 90);
// top right arc
arc.X = bounds.Right - diameter;
path.AddArc(arc, 270, 90);
// bottom right arc
arc.Y = bounds.Bottom - diameter;
path.AddArc(arc, 0, 90);
// bottom left arc
arc.X = bounds.Left;
path.AddArc(arc, 90, 90);
path.CloseFigure();
return path;
}
像這樣的事情可能會更好。 嘗試使用curveSize
各種值。 請注意, curveSize
必須介於 1 和 rect.Width/4 和 rect.Height/4 的最小值之間:
public static GraphicsPath RoundedRect(Rectangle rc, float curveSize)
{
if (curveSize < 0 || curveSize > rc.Height / 4.0f || curveSize > rc.Width / 4.0f)
curveSize = 0;
var result = new GraphicsPath();
if (curveSize > 0)
{
float size4 = curveSize * 4;
result.AddArc(rc.Right - size4, rc.Top, size4, size4, 270, 90);
result.AddArc(rc.Right - size4, rc.Bottom - size4, size4, size4, 0, 90);
result.AddArc(rc.Left, rc.Bottom - size4, size4, size4, 90, 90);
result.AddArc(rc.Left, rc.Top, size4, size4, 180, 90);
result.CloseFigure();
}
else if (rc.Width > 0 && rc.Height > 0)
{
result.AddRectangle(rc);
}
return result;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.