嘿伙计们......有数学问题。试图布局一个灰色框网格,我想在上面加载缩略图。尝试加载第4个缩略图时,我一直收到错误消息。如果删除xml中的第4个人节点,它可以正常工作,但添加第4个节点会给我一个错误吗?
代码如下。
非常感谢任何帮助。
package
{
import flash.display.MovieClip;
import flash.geom.Point;
public class People extends MovieClip
{
public function People()
{
draw();
}
public function draw():void
{
var colors:Array = [0xFF0000, 0x009900];
var rows:Array = [];
var xml:XML = new XML("<data><navitem><person>person1</person><person>person2</person><person>person3</person><person>person4</person></navitem><navitem><person>person1</person><person>person2</person></navitem></data>");
var j;
var i;
for (i in xml.navitem) {
rows.push(new MovieClip());
var totRows:Number = 0;
for (j in xml.navitem[i].person) {
if(j % 3 == 1){
totRows++
}
}
if (totRows == 0) {
totRows = 1
}
rows[i].grid = createGrid(3, totRows, 85, 85,25, 25);
for (j in rows[i].grid) {
var mc:MovieClip = new MovieClip();
with (mc) {
graphics.beginFill(0, .5);
graphics.drawRect(0, 0, 85, 85);
graphics.endFill();
}
mc.x = rows[i].grid[j].x;
mc.y = rows[i].grid[j].y;
rows[i].addChild(mc);
}
// add the people
for (j in xml.navitem[i].person) {
var mc:MovieClip = new MovieClip();
with (mc) {
graphics.beginFill(colors[i], .5);
graphics.drawRect(0, 0, 85, 85);
graphics.endFill();
}
mc.x = rows[i].grid[j].x;
mc.y = rows[i].grid[j].y;
rows[i].addChild(mc);
}
addChild(rows[i]);
rows[i].y = i > 0 ? rows[(i - 1)].y + rows[(i - 1)].height + 25 : 0;
}
}
private function createGrid($columns:int, $rows:int, $xSpacing:int, $ySpacing:int, $xPadding:int, $yPadding:int, $leftToRight:Boolean = true):Array
{
var arr:Array = new Array();
var pt:Point;
var row:Number;
var col:Number;
var num:int = ($columns * $rows);
for (var i:int = 0; i < num; i++)
{
pt = new Point();
if ($leftToRight)
{
row = (i % $columns);
col = Math.floor(i / $columns);
pt.x = (row * ($xSpacing + $xPadding));
pt.y = (col * ($ySpacing + $yPadding));
}
else
{
row = (i % $rows);
col = Math.floor(i / $rows);
pt.x = (col * ($xSpacing + $xPadding));
pt.y = (row * ($ySpacing + $yPadding));
}
arr.push(pt);
}
return arr;
}
}
}
答案 0 :(得分:2)
您已将列数硬编码为3
rows[i].grid = createGrid(3, totRows, 85, 85,25, 25);
将其更改为:
rows[i].grid = createGrid(xml.navitem[i].person.length(), totRows, 85, 85,25, 25);
顺便说一句,请考虑使用
for(i = 0; i < xml.navitem.length(); i++)
而不是
for (i in xml.navitem)
并输入var i:Number;
目前i
的值是"0"
,"1"
之类的字符串 - 它会在意外点导致错误,而且可能难以调试。
更新: 将行数初始化为1而不是零:
var totRows:Number = 1;
答案 1 :(得分:1)
我找到了答案。不得不改变条件语句:
var totRows:int;
if (xml.navitem[i].person.length() % 3 == 0){
totRows = xml.navitem[i].person.length() / 3;
} else {
totRows = xml.navitem[i].person.length() / 3 + 1;
}