2017-07-29 37 views
2

我希望我的UserControl自動更新其Region屬性。我希望它是合併在一起的兒童控制區域的組合。爲UserControl創建組合區域

這裏是我到目前爲止有:

protected override void OnSizeChanged(EventArgs e) 
{ 
    base.OnSizeChanged(e); 

    Region region = new Region(new Rectangle(Point.Empty, Size.Empty)); 

    foreach (Control control in Controls) 
    { 
     if (control.Region != null) 
      region.Union(control.Region); 
     else 
      region.Union(control.Bounds); 
    } 

    Region = region; 
    Invalidate(); 
} 

問題是,這是行不通的:行region.Union(control.Region);必須改變,因爲地區不包括有關左側與頂端的控制的偏移信息。

我該怎麼辦?

+0

如何創建控件的地區?通過GraphicsPath?一氣呵成還是漸進? – TaW

+0

@Taw - 是的,一次使用GraphicsPath。有關係嗎? – walruz

+0

您可以存儲這些GraphicsPaths,也許在標籤中,然後將它們用於聯盟。你可以用Matrix來移動它們。 – TaW

回答

1

您可以選擇或者Rectangles實際上構成Region。你可以通過GetRegionScans獲得。你可以在this post中看到它們。

或使用GraphicsPaths你的子控件Regions發源於..

在這兩種方法,你可以移動控件由它的位置區域數據:無論是通過偏移每個矩形或通過翻譯整的GraphicsPath 。

這裏是用於第一方法的代碼例如:

if (control.Region != null) 
{ 
    Matrix matrix = new Matrix(); // default, unscaled screen-resolution matrix 
    var rex = control.Region.GetRegionScans(matrix); // get rectangles 
    foreach (var r in rex) // use each of them 
    { 
     r.Offset(control.Location); // move by the location offsets 
     region.Union(r); 
    } 
else 
{ 
    region.Union(control.Bounds); 
} 

的問題是,這趨向於得到慢與「垂直」 大小Region複雜形狀..

其他方式是跟蹤子控件的GraphicsPaths

假設一類PathControl與控件屬性

public GraphicsPath path { get; set; } 

也許你可以改變環路這樣:

foreach (Control control in Controls) 
{ 
    if (control is PathControl) 
    { 
     // use a clone, so the original path won't be changed! 
     GraphicsPath gp = (GraphicsPath)(control as PathControl).path.Clone(); 

     Matrix matrix = new Matrix(); 
     matrix.Translate(control.Left, control.Top); 
     gp.Transform(matrix); // here we move by the location offsets 

     region.Union(gp); 
    else 
    { 
     region.Union(control.Bounds); 
    } 
}