[英]How do I create 2 rounded corners in winforms with borders?
I have a code that helped me make a rounded corner, border-less WinForm
. 我有一个代码可以帮助我制作一个圆角的,无边框的
WinForm
。 It works fine but the thing is that it has no borders, so I want to add rounded borders to it. 它工作正常,但事实是它没有边框,因此我想向其中添加圆形边框。 Also, I only want
TopLeft
and BottomRight
corners to be rounded. 另外,我只希望将
TopLeft
和BottomRight
角进行圆角处理。
This is my current code: 这是我当前的代码:
public partial class mainForm : Form
{
[DllImport("Gdi32.dll", EntryPoint = "CreateRoundRectRgn")]
private static extern IntPtr CreateRoundRectRgn
(
int nLeftRect, // x-coordinate of upper-left corner
int nTopRect, // y-coordinate of upper-left corner
int nRightRect, // x-coordinate of lower-right corner
int nBottomRect, // y-coordinate of lower-right corner
int nWidthEllipse, // height of ellipse
int nHeightEllipse // width of ellipse
);
}
public Form1()
{
InitializeComponent();
this.FormBorderStyle = FormBorderStyle.None;
Region = System.Drawing.Region.FromHrgn(CreateRoundRectRgn(0, 0, Width, Height, 20, 20));
}
It is easily achievable in WPF
but how do I get that in WinForms
? 在
WPF
很容易实现,但是如何在WinForms
呢?
What should I do? 我该怎么办?
You can draw border manually in client area. 您可以在客户区域中手动绘制边框。 It's very simple but you will have to take care to layout children controls with some margin.
这很简单,但您必须注意一定程度地布局子控件。
And it is still a challenge though, because there is only Graphics.FillRegion and no way to draw outline or DrawRegion
method. 但是,这仍然是一个挑战,因为只有Graphics.FillRegion ,没有办法绘制轮廓或
DrawRegion
方法。
We can create GraphicsPath
and draw it with Graphics.DrawPath
, but creating it is tricky, eg this implementation doesn't match to to created with CreateRoundRectRgn()
method. 我们可以创建
GraphicsPath
并使用Graphics.DrawPath
绘制,但是创建起来很棘手,例如, 该实现与使用CreateRoundRectRgn()
方法创建的实现不匹配。
So there is a trick with 2 regions: bigger region with border color and smaller region inside with client color. 因此,有一个技巧有2个区域:较大的区域带有边框颜色,较小的区域带有客户颜色。 This will leave little bit of outer region which will visually creates a border.
这将留下少量的外部区域,这将在视觉上创建边框。
readonly Region _client;
public Form1()
{
InitializeComponent();
// calculate smaller inner region using same method
_client = Region.FromHrgn(CreateRoundRectRgn(1, 1, Width - 1, Height - 1, 20, 20));
Region = Region.FromHrgn(CreateRoundRectRgn(0, 0, Width, Height, 20, 20));
}
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
// FillRectangle is faster than FillRegion for drawing outer bigger region
// and it's actually not needed, you can simply set form BackColor to wanted border color
// e.Graphics.FillRectangle(Brushes.Red, ClientRectangle);
e.Graphics.FillRegion(Brushes.White, _client);
}
Result: 结果:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.