Asset Scaling and Positioning

0
99

You can scale and position your assets dynamically once you have collected the device’s capabilities and current state. As a general rule, do not use absolute or hardcoded values.

Use the screenDPI property to convert inches to pixels, the unit needed for assets:

function toPixels(inches:Number):int {
return Math.round(Capabilities.screenDPI*inches);
}

Here is the same function using the metric system to convert millimeters to pixels, which is easier for those educated outside the United States:

function toPixels(mm:Number):int {
return Math.round(Capabilities.screenDPI*(mm/25.4));
}

Shift your thinking to inches to determine the dimension you want. Then use it to convert your asset to pixels. The following creates a sprite of 10×10 inches, or 100×100 pixels:

var box:Sprite = new Sprite();
box.graphics.beginFill(0x999999);
var pos:int = toPixels(10);
box.graphics.drawRect(0, 0, pos, pos);
box.graphics.endFill();
addChild(box);

Dynamic positioning

Once the art is created at the right size, position it dynamically.

In this example, the sprite is positioned in the center of the screen. Adjust the position to offset it in relation to the registration point (see Figure 5-1):

// registration point is at upper-left corner as defined earlier
box.x = stage.stageWidth * 0.5 – box.width*0.5;
box.y = stage.stageHeight * 0.5 – box.height*0.5;

For an object whose registration point is in the middle, the x and y positions do not need an offset (see Figure 5-2):

box.x = stage.stageWidth;
box.y = stage.stageHeight;

In this example, a sprite with a registration point at the upper left is positioned at the bottom of the screen (see Figure 5-3):

box.y = stage.stageHeight – box.height;

Offsetting the sprite in relation to the registration point

Sprite whose registration point is in the middle, requiring no offset 52 |

Sprite whose registration point is at the upper left, positioned at the bottom of the screen

In this example, the sprite is positioned one-quarter of the way down from the upperleft corner (see Figure 5-4):

box.x = stage.stageWidth*0.25;
box.y = stage.stageHeight*0.25;

Sprite positioned one-quarter of the way down the upper-left corner

If your application is displayed full screen, use stage.FullScreenWidth and stage.Full ScreenHeight instead.

Sometimes the simplest solution is to group your art and center it, and then fill the borders with a colored background as for a picture frame.

Using a grid layout as a starting point is a good approach for multiple screen deployment. The website at http://960.gs/ provides some ideas.