2015年3月30日 星期一

[Corona SDK] graphics.newImageSheet 怎麼用?

如果我們要放上一張圖,
只要使用display.newImage()去載入圖檔即可,
圖檔很多時,程式就會顯得很繁瑣,

如果這些圖是有高度相關性,甚至大小也都相同,
那麼使用graphics.newImageSheet()會是一個更好的選擇,
假設我們要畫上撲克牌的52張牌,
我們先把所以牌放在同一張圖裡,如下:
card.png
程式代碼:
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
graphics.newImageSheet( image_name, options )只要傳進圖檔名稱和參數options即可,
options裡的sheetContentWidthsheetContentHeight是原始圖檔的大小,不用指定也可以,
options裡的widthheight是每張小圖的大小,
options裡的numFrames是圖檔裡小圖的數量,

然後在display.newImage()傳入剛剛建立的image sheet以及想要顯示第幾個小圖
執行結果如下:
View As 1080x920
如果每張小圖的大小不一樣,
那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...
    },

}

3 則留言:

  1. 請問我有一動畫再讓他在被觸碰到時發出音效,請問要如何做?? 謝謝!!
    local bus1 = graphics.newImageSheet( "bus1.png", { width=234, height=134, numFrames=8 } )
    local instance_bus1 = display.newSprite( bus1, { name="bus1", start=1, count=8, time=800 } )
    instance_bus1.x = 1024+115
    instance_bus1.y = 365-65
    instance_bus1:play()
    transition.to(instance_bus1, {time=8000, delay=4000, x=-155, y=instance_bus1.y, rotation=0, transition=easing.linear, iterations=0})

    回覆刪除
    回覆
    1. 要偵測碰撞,需要將物體加入physics.addBody(instance_bus1,....),然後再local collision 或者global collision裡加入audio.play()

      刪除