Skip to content

Instantly share code, notes, and snippets.

@enue
Created January 19, 2017 23:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save enue/fff572aa67c812304f7d65ae1ba0e029 to your computer and use it in GitHub Desktop.
Save enue/fff572aa67c812304f7d65ae1ba0e029 to your computer and use it in GitHub Desktop.
[Unity] Rectの合成
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Linq;
namespace TSKT
{
public class CombineRect
{
List<Rect> rects = new List<Rect>();
public List<Rect> Rects
{
get
{
return rects;
}
}
public void Append(Rect rect)
{
if (rects.Any(_ => Contains(_, rect)))
{
return;
}
while (true)
{
rects.RemoveAll(_ => Contains(rect, _));
var combined = false;
for (int i = 0; i < rects.Count;)
{
Rect combinedRect;
if (TryCombine(rects[i], rect, out combinedRect))
{
rect = combinedRect;
rects.RemoveAt(i);
combined = true;
continue;
}
if (TryCombine(rect, rects[i], out combinedRect))
{
rect = combinedRect;
rects.RemoveAt(i);
combined = true;
continue;
}
++i;
}
if (!combined)
{
break;
}
}
rects.Add(rect);
}
static bool Contains(Rect a, Rect b)
{
return a.Contains(new Vector2(b.xMin, b.yMin), true)
&& a.Contains(new Vector2(b.xMax, b.yMax), true);
}
static bool TryCombine(Rect a, Rect b, out Rect result)
{
if (a.yMin == b.yMin
&& a.yMax == b.yMax
&& a.xMin <= b.xMin
&& b.xMin <= a.xMax
&& a.xMax <= b.xMax)
{
result = Rect.MinMaxRect(a.xMin, a.yMin, b.xMax, b.yMax);
return true;
}
if (a.xMin == b.xMin
&& a.xMax == b.xMax
&& a.yMin <= b.yMin
&& b.yMin <= a.yMax
&& a.yMax <= b.yMax)
{
result = Rect.MinMaxRect(a.xMin, a.yMin, b.xMax, b.yMax);
return true;
}
result = Rect.zero;
return false;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment