C#中的所有控件都有Region属性,在设置Region属性时,注意Region的参考系是以所设置的控件的左上角坐标,即 Custom.Location。
所以,在设置Region的GraphicsPath时,其左上角坐标始终为(0,0)
错误范例:
设置pB_headimg的Region为圆滑矩形。
private GraphicsPath GetRectPath(Rectangle rect,int radius)
{
int diameter = radius;
Rectangle arcRect = new Rectangle(rect.Location, new Size(diameter, diameter));
GraphicsPath path = new GraphicsPath();
// 左上角
path.AddArc(arcRect, 180, 90);
// 右上角
arcRect.X = rect.Right - diameter;
path.AddArc(arcRect, 270, 90);
// 右下角
arcRect.Y = rect.Bottom - diameter;
path.AddArc(arcRect, 0, 90);
// 左下角
arcRect.X = rect.Left;
path.AddArc(arcRect, 90, 90);
path.CloseFigure();//闭合曲线
return path;
}
private void setPicbox()
{
GraphicsPath formPath = new GraphicsPath();
//错误使用控件的位置坐标,即使用了以窗口左上角为参考系
Rectangle rect = new Rectangle(pB_headimg.Location.X,pB_headimg.Location.Y,pB_headimg.Width, pB_headimg.Height);
formPath = GetRectPath(rect, 5);
pB_headimg.Region = new Region(formPath);
}
结果:
Region的范围为( pB_headimg.Right ,pB_headimg.Bottom ,pB_headimg.Width ,pB_headimg.Height ) 超出了pB_headimg的范围,所以pB_headimg消失了。