2015年4月1日 星期三

[Corona SDK] Why the image position is not as expected when we use display.newImage() ? - the usage of anchor

If we want to show one picture, we only need to:
local background = display.newImage( "320x480.jpg",0,0)
It's simple, only need one line code.
Check the result in Simulator...
anchorX=0.5, anchorY=0.5
Well... it is weird.
The position of picture seems to be incorrect.

It is because that every object has its own what called anchorX and anchorY. 
anchor is the center of action, no matter that you want to move it, scale up/down it or rotate it.

The picture shown above is captured from the coronalabs website.
anchorX/anchorY is ranged from top left corner (0,0) to bottom right corner (1,1).
The default value is (0.5, 0.5) which is the center of object.
(Note that the values of anchor are the ratio of object size.)
That is, display.newImage( "320x480.jpg",0,0) will put the center of picture to the position (0,0), which (0,0) are the x/y coordinate values.
That's why we got for the first picture shown above.

So..how can we adjust it?
local background = display.newImage( "320x480.jpg",0,0)
background.anchorX=0
background.anchorY=0
We just need to set the anchor to be (0,0).

anchorX = 0, anchorY = 0
However, you may find that in most demo codes, they do not do that in this way.
In general, we will not modify the anchor unless it is necessary.
Since the position is relative, we can use the following method:
local xpos = display.contentCenterX
local ypos = display.contentCenterY
local background = display.newImage( "320x480.jpg", xpos, ypos )
Or you may see some people coding in this way.
local xpos = display.contentWidth/2
local ypos = display.contentHeight/2
local background = display.newImage( "320x480.jpg", xpos, ypos )
They are doing in the similar way - locate the center of picture to the center of the screen.
The result will be as expected if we are doing so.

沒有留言:

張貼留言