获取 Bounds

通过显示对象的 getBounds 方法可以获取对象的 bounds:

var texture = Tiny.RenderTexture.create(10, 10);
var sprite = new Tiny.Sprite(texture);
var bounds = sprite.getBounds();
console.log(bounds);
//=> {x: 0, y: 0, width: 10, height: 10, type: 1}

包含多个对象的容器,得到的 bounds 是它们的集合:

var container = new Tiny.Container();
var g1 = new Tiny.Graphics().beginFill(0xFF0000).drawCircle(0, 0, 50, 50);
var g2 = new Tiny.Graphics().beginFill(0xFFFF00).drawCircle(0, 0, 120, 120);
g1.setPosition(60, 60);
g2.setPosition(170, 170);
container.addChild(g1);
container.addChild(g2);
var bounds = container.getBounds();
console.log(bounds);
//=> {x: 10, y: 10, width: 280, height: 280, type: 1}

容器中未显示的对象不会计算:

var container = new Tiny.Container();
var texture = Tiny.RenderTexture.create(33, 22);
var sprite = new Tiny.Sprite(texture);
container.addChild(sprite);
sprite.setVisible(false);
var bounds = container.getBounds();
console.log(bounds);
//=> {x: 0, y: 0, width: 0, height: 0, type: 1}

容器中透明度为0的对象会被计算:

var container = new Tiny.Container();
var texture = Tiny.RenderTexture.create(33, 22);
var sprite = new Tiny.Sprite(texture);
container.addChild(sprite);
sprite.setOpacity(0);
var bounds = container.getBounds();
console.log(bounds);
//=> {x: 0, y: 0, width: 33, height: 22, type: 1}

单个对象未显示或透明度为0均会被计算:

var texture = Tiny.RenderTexture.create(10, 10);
var sprite = new Tiny.Sprite(texture);
sprite.setOpacity(0);
// 或
// sprite.setVisible(false);
var bounds = sprite.getBounds();
console.log(bounds);
//=> {x: 0, y: 0, width: 10, height: 10, type: 1}

注意:

  • 使用getBounds前一定要保证图片资源加载完成的,要不然获取的一定是:{x: 0, y: 0, width: 1, height: 1, type: 1}

LocalBounds

区别于 getBoundsgetLocalBounds 个获取的是真实的 bounds,就好像显示对象没有应用 transform 一样

var bounds = sprite.getBounds();
var localBounds = sprite.getLocalBounds();
console.log(bounds);
//=> {x: 0, y: 0, width: 300, height: 300, type: 1}
console.log(localBounds);
//=> {x: -0, y: -0, width: 300, height: 300, type: 1}

sprite.setScale(0.5);
var bounds = sprite.getBounds();
var localBounds = sprite.getLocalBounds();
console.log(bounds);
//=> {x: 0, y: 0, width: 150, height: 150, type: 1}
console.log(localBounds);
//=> {x: -0, y: -0, width: 300, height: 300, type: 1}

注意:

  • 如果 Application 的 renderer.resolution 不为 1,请使用 getLocalBounds 来获取 Bounds
  • 如果显示对象的父集或自己应用过 transform 变换,请使用父集的 getLocalBounds 来获取 Bounds
  • 简单点就是如果 getBounds 不符合预期就用 getLocalBounds