【问题标题】:Create combined Region for UserControl为 UserControl 创建组合区域
【发布时间】:2017-07-29 17:04:55
【问题描述】:

我希望我的 UserControl 自动更新其 Region 属性。我希望它是子控件区域合并在一起的组合。

这是我目前所拥有的:

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); 行必须更改,因为 Region 不包含有关控件左偏移和上偏移的信息。

我能做什么?

【问题讨论】:

  • 如何创建控件的区域?通过图形路径?一次性还是逐步?
  • @Taw - 是的,一次性使用 GraphicsPath。有关系吗?
  • 您可以将这些 GraphicsPaths 存储在标签中,然后将它们用于联合。您可以使用矩阵移动它们。
  • @TaW - 我想知道 GetRegionScans 方法在这种情况下是否有用?
  • 可以,但是根据控件的大小,它可能会变得非常慢。请参阅here 进行讨论!

标签: c# winforms region


【解决方案1】:

您可以选择或者选择实际上构成RegionRectangles。您可以通过GetRegionScans 获取它们。你可以在this post看到他们。

使用GraphicsPaths你的孩子控件'Regions来自..

在这两种方法中,您都可以按位置移动控件的区域数据:通过偏移每个矩形或平移整个图形路径。

这里是第一种方法的代码示例:

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);
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-12
    • 1970-01-01
    相关资源
    最近更新 更多