如何使用 Phaser 制作带有动态文本的按钮?
How to make a button with dynamic text using Phaser?
创建 3 个设计相同但文本不同(短文本、中等长度文本、长文本)的按钮的解决方法是什么:
a) 我需要 3 张不同的图片作为背景吗?如果我不知道文本的长度怎么办?
b) 或者我可以使用单个图像 shrink/stretch 它 horizontally/vertically 当文本需要 more/less space 以某种方式适应时?
我希望每个按钮不需要数百张图片:)
我只是一个初学者。最佳做法是什么?
以下是我创建响应式按钮和文本的方法:
buttonSprite2 = game.add.sprite(352, 76,'button');
buttonSprite2.position.set(200, 0);
buttonSprite2.inputEnabled = true;
buttonSprite2.events.onInputDown.add(listener2, this);
var style = { font: "32px Arial", fill: "#ffffff", wordWrap: true, align: "center", backgroundImage:'button'};
buttonText2 = game.add.text(0, 0, "stop text", style);
buttonText2.wordWrapWidth = game.world.width - 400;
// trying to center the text within the button
buttonText2.position.set(buttonSprite2.x + 100, buttonSprite2.y+15);
// trying to make the button responsive
if(buttonText2.width < game.world.width - 400){
buttonSprite2.width = buttonText2.width + 200;
}
else{
buttonSprite2.width = game.world.width - 300;
buttonSprite2.height = buttonText2.height + 30;
}
您只需要 load
(在 preload
函数中)图像一次。但是您需要 add
(在 create
函数中)3 个图像用于 3 个按钮。
用于根据文本大小更改此按钮图像的大小。首先添加图像,然后添加文本。现在,添加文本后,检查该文本对象的 height
或 width
,并根据文本的 height
和 width
更改按钮图像的大小。
您可以定义单独的函数来执行此操作。所以,如果你有太多的按钮,你可以摆脱冗余代码。
创建 3 个设计相同但文本不同(短文本、中等长度文本、长文本)的按钮的解决方法是什么:
a) 我需要 3 张不同的图片作为背景吗?如果我不知道文本的长度怎么办?
b) 或者我可以使用单个图像 shrink/stretch 它 horizontally/vertically 当文本需要 more/less space 以某种方式适应时?
我希望每个按钮不需要数百张图片:)
我只是一个初学者。最佳做法是什么?
以下是我创建响应式按钮和文本的方法:
buttonSprite2 = game.add.sprite(352, 76,'button');
buttonSprite2.position.set(200, 0);
buttonSprite2.inputEnabled = true;
buttonSprite2.events.onInputDown.add(listener2, this);
var style = { font: "32px Arial", fill: "#ffffff", wordWrap: true, align: "center", backgroundImage:'button'};
buttonText2 = game.add.text(0, 0, "stop text", style);
buttonText2.wordWrapWidth = game.world.width - 400;
// trying to center the text within the button
buttonText2.position.set(buttonSprite2.x + 100, buttonSprite2.y+15);
// trying to make the button responsive
if(buttonText2.width < game.world.width - 400){
buttonSprite2.width = buttonText2.width + 200;
}
else{
buttonSprite2.width = game.world.width - 300;
buttonSprite2.height = buttonText2.height + 30;
}
您只需要 load
(在 preload
函数中)图像一次。但是您需要 add
(在 create
函数中)3 个图像用于 3 个按钮。
用于根据文本大小更改此按钮图像的大小。首先添加图像,然后添加文本。现在,添加文本后,检查该文本对象的 height
或 width
,并根据文本的 height
和 width
更改按钮图像的大小。
您可以定义单独的函数来执行此操作。所以,如果你有太多的按钮,你可以摆脱冗余代码。