LoginSignup
1
0

More than 1 year has passed since last update.

【Playdate】9スライスウィンドウを表示する

Posted at

前回のプロジェクトを更に改造します。
入力したテキストの背景に9スライスに対応したウィンドウを表示してみます。

main.lua
import "CoreLibs/object"
import "CoreLibs/graphics"
import "CoreLibs/sprites"
import "CoreLibs/timer"

import "CoreLibs/keyboard"
import "CoreLibs/qrcode"
import "CoreLibs/nineslice"

local gfx <const> = playdate.graphics

local inputText = "Edit PressA"
local qrImage = nil
local qrSprite = nil
local window = nil

function QRDone(image, errorMessage)
	qrImage = image
end

function myGameSetUp()
	playdate.keyboard.textChangedCallback = function()
		inputText = playdate.keyboard.text
		gfx.sprite.redrawBackground()
	end
	
	playdate.keyboard.keyboardDidHideCallback = function()
		print(playdate.keyboard.text)
		gfx.generateQRCode(inputText, nil, QRDone)
	end
	
	qrSprite = gfx.sprite.new( qrImage )
	qrSprite:moveTo( 70, 120 )
	qrSprite:add()
	
	-- 9slice
	window = gfx.nineSlice.new("Images/window_9slice", 8, 8, 48, 48)
	
	gfx.sprite.setBackgroundDrawingCallback(
		function( x, y, width, height )
			gfx.drawText('_'..inputText..'_', 20, 20)
			local width, height = gfx.getTextSize('_'..inputText..'_')
			window:drawInRect(20 - 8, 20 - 8, width + 16, height + 16)
		end
	)
end

myGameSetUp()

function playdate.update()
	
	if playdate.buttonIsPressed(playdate.kButtonA) then
		playdate.keyboard.show(inputText)
	end
	
	qrSprite:setImage(qrImage)
	gfx.sprite.update()
	playdate.timer.updateTimers()
end

9スライスの表示にはimport "CoreLibs/nineslice"でAPIを読み込む必要があります。
更に今回window_9sliceという9スライス用のウィンドウ画像を制作しました。

window_9slice.png
window_9slice.png
それぞれ四隅のサイズは8x8の領域となります。

これをwindowというnineSliceオブジェクトとして以下のように新規作成します。
window = gfx.nineSlice.new("Images/window_9slice", 8, 8, 48, 48)

テキストの描画サイズはgfx.getTextSize(str)で取得するしています。widthとheightをそれぞれ返します。
最後にウィンドウの描画です。
window:drawInRect(20 - 8, 20 - 8, width + 16, height + 16)とウィンドウの四隅のサイズを考慮して記述しています。

これで編集して以下のような形で動的にウィンドウのサイズが変わっても四隅のグラフィックが崩れることなく可変できるようになりました。

変更前

変更後 テキストに応じてウィンドウも可変している

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0