码迷,mamicode.com
首页 > 其他好文 > 详细

压缩UI深度的代码实现

时间:2015-06-19 16:40:20      阅读:106      评论:0      收藏:0      [点我收藏+]

标签:

记录一下,或许同样使用深度的NGUI以后会用到。

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

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

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

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

代码实现如下:

 1 var depthList:Vector.<int> = getDepthList(this);
 2 //打印结果
 3 for(var i:int = 0; i < depthList.length; i++)
 4 {
 5     trace("元件\"" + getChildAt(i).name + "\"的深度是: " + depthList[i]);
 6 }
 7 
 8 /**
 9  * 获取指定容器下的最小深度列表,按子对象z轴由下到上的顺序排列其深度数值.
10  */
11 function getDepthList(target:DisplayObjectContainer):Vector.<int>
12 {
13     var result:Vector.<int> = new Vector.<int>(target.numChildren, true);
14     //结果数组使用 0 填充
15     var i:int;
16     for(i = 0; i < target.numChildren; i++)
17     {
18         result[i] = 0;
19     }
20     
21     for(i = 0; i < target.numChildren; i++)
22     {
23         var child:DisplayObject = target.getChildAt(i);
24         getChildDepth(target, child, i, result);
25     }
26     
27     return result;
28 }
29 
30 function getChildDepth(target:DisplayObjectContainer, child:DisplayObject, index:int, result:Vector.<int>):void
31 {
32     for(var i:int = 0; i < target.numChildren; i++)
33     {
34         var targetChild:DisplayObject = target.getChildAt(i);
35         //过滤掉自己
36         if(targetChild == child)
37         {
38             continue;
39         }
40         //只处理位于当前显示对象下方的显示对象
41         if(i < index)
42         {
43             //只处理相互存在重叠的显示对象
44             if(targetChild.hitTestObject(child))
45             {
46                 //获取深度, 下方所有对象的深度必然都已经获得, 直接 + 1 即可
47                 var depth:int = result[i] + 1;
48                 //如果存在更大的深度就使用更大的深度
49                 if(result[index] < depth)
50                 {
51                     result[index] = depth;
52                 }
53             }
54         }
55     }
56 }

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

http://pan.baidu.com/s/135JHG

压缩UI深度的代码实现

标签:

原文地址:http://www.cnblogs.com/hammerc/p/4588996.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!