2015年4月6日 星期一

[Corona SDK] How to use graphics.newImageSheet ?

When we want to draw a picture, we can use display.newImage() to load the picture file.
It is quite simple and easy.
However, if we want to draw a lot of pictures, use display.newImage() to load the picture one by one would be tedious.

If these pictures are related, and even they have the same sizes,
to use graphics.newImageSheet()  is a better option.

Assume that we want to draw 52 pictures of poker cards.
Let's us put all the 52 pictures in one picture name "card.png", shown as below:

card.png
Then we can show all the 52 pictures with following codes:
display.setDefault( "background", 0.2, 0.5, 0.2 )

local frames_width = 73
local frames_height = 98
local total_frames = 52
local image_name = "card.png"
local scaleRatio = 0.6
local options =
{
 width = frames_width,
 height = frames_height,
 numFrames = total_frames,
 --sheetContentWidth = 754,  -- width of original 1x size of entire sheet
    --sheetContentHeight = 311   -- height of original 1x size of entire sheet
}

local sheet = graphics.newImageSheet( image_name, options )
cardGroup = {}
for i=0,3,1 do
 for j=1,13,1 do
  cardGroup[i*13+j] = display.newImage( sheet,i*13+j)
  cardGroup[i*13+j]:scale( scaleRatio, scaleRatio )
 end
end
--------------------------------------------------------------------------------
for i=0,3,1 do
 for j=1,7,1 do 
 cardGroup[i*13+j]:translate( (frames_width*scaleRatio+2)*(j-1)+(frames_width*scaleRatio+2)/2,(frames_height*scaleRatio+2)/2+(i*2)*(frames_height*scaleRatio+2)) 
 end 
 for j=1,6,1 do 
 cardGroup[i*13+j+7]:translate( (frames_width*scaleRatio+2)*(j-1)+(frames_width*scaleRatio+2)/2,(frames_height*scaleRatio+2)/2+(i*2+1)*(frames_height*scaleRatio+2)) 
 end 
end
For graphics.newImageSheet( image_name, options ), we only need to pass in the file name and options.
The parameters sheetContentWidth and sheetContentHeight in options are the size of the picture (e.g card.png) . We can leave them without specified if we don't want to scale it.
The parameters width and height are the size of thumbnails (e.g. the size of one card).
The parameter numFrames is the number of thumbnails (e.g. 52 in our case).

When we want to display any card, we can pass in the image sheet we just built and the card index to display.newImage().
The result of the codes:
View As 1080x920
What if the size of thumbnails are not the same?
In such case, we have to specify the size for each thumbnails in the options:
local options =
{
    --array of tables representing each frame (required)
    frames =
    {
        -- FRAME 1:
        {
            --all parameters below are required for each frame
            x = 2,
            y = 70,
            width = 50,
            height = 50
        },

        -- FRAME 2:
        {
            x = 2,
            y = 242,
            width = 50,
            height = 52
        },

        -- FRAME 3 and so on...
    },

}

沒有留言:

張貼留言