您的位置:首页 > 产品设计 > UI/UE

压缩UI深度的代码实现

2015-06-19 16:07 423 查看
记录一下,或许同样使用深度的NGUI以后会用到。

目前的项目的UI是用Stage3D实现的,采用了类似NGUI填写深度来确定覆盖关系,但同时可以使用的深度是有一个固定范围的,导致的问题是如果UI过多深度可能就会不够用,对于这种情况可以写段代码进行深度的压缩,比如如果两个图片相互之间不会重叠则可以使用同一个深度。

相对于传统的显示列表,每个深度都唯一的情况不同,压缩后的深度可以有多个是相同的,但是相同深度的图片不能重叠,否则会出现随机覆盖的问题。

压缩深度的前提条件是所有UI的遮罩顺序都必须是提前设定好的。

基本的思路如下:从最底层的UI开始逐个处理到最上层的UI,如果发现有重叠的UI,且这个重叠的UI是在自己的下方,那么我的深度就是这个UI的深度+1,同时可能我下方会有多个UI都和我重叠,所以我的深度应该是下方所有和我重叠的UI的深度的最大值+1。

代码实现如下:

var depthList:Vector.<int> = getDepthList(this);
//打印结果
for(var i:int = 0; i < depthList.length; i++)
{
trace("元件\"" + getChildAt(i).name + "\"的深度是: " + depthList[i]);
}

/**
* 获取指定容器下的最小深度列表,按子对象z轴由下到上的顺序排列其深度数值.
*/
function getDepthList(target:DisplayObjectContainer):Vector.<int>
{
var result:Vector.<int> = new Vector.<int>(target.numChildren, true);
//结果数组使用 0 填充
var i:int;
for(i = 0; i < target.numChildren; i++)
{
result[i] = 0;
}

for(i = 0; i < target.numChildren; i++)
{
var child:DisplayObject = target.getChildAt(i);
getChildDepth(target, child, i, result);
}

return result;
}

function getChildDepth(target:DisplayObjectContainer, child:DisplayObject, index:int, result:Vector.<int>):void
{
for(var i:int = 0; i < target.numChildren; i++)
{
var targetChild:DisplayObject = target.getChildAt(i);
//过滤掉自己
if(targetChild == child)
{
continue;
}
//只处理位于当前显示对象下方的显示对象
if(i < index)
{
//只处理相互存在重叠的显示对象
if(targetChild.hitTestObject(child))
{
//获取深度, 下方所有对象的深度必然都已经获得, 直接 + 1 即可
var depth:int = result[i] + 1;
//如果存在更大的深度就使用更大的深度
if(result[index] < depth)
{
result[index] = depth;
}
}
}
}
}


附上测试文件,可以拖拽UI来查看压缩后的深度。

http://pan.baidu.com/s/135JHG
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: