How to make a button with dynamic text using Phaser? - phaser-framework

What is the workaround to create 3 buttons with the same design but different texts (short text, medium length text, long text):
a) do I need 3 different images as a background ? What if i don’t know the length of the text ?
b) or I can use a single image and shrink/stretch it horizontally/vertically somehow when a text needs more/less space to fit in?
I hope i don’t need hundreds of images for each button :)
I’m just a beginner. What is the best practice ?
Here is how I create a responsive button and text:
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;
}

You need to load(in preload function) image only once. But you need to add(in create function) 3 images for 3 buttons.
For changing size of this button images according to text size. First you add image then add text. Now, after adding text, check for height or width of that text object and change size of the button image according to the height and width of text.
You may define seperate function to do this. So, you can get rid of redundant code if you have too many buttons.

Related

fabric.js: How to set stroke thickness of selection box and controls?

In fabric.js, how do you adjust stroke thickness for the object selection box and control handles?
There's a bunch of customization options available, however it isn't clear on how you can customized stroke thickness. Is it possible, perhaps through an indirect way?
Note: The properties selectionColor, selectionBorderColor, selectionLineWidth are misleading... they have to do with the temporary selection box that appears when attempting to do a fresh drag-select across the canvas. Once your selection is made, it disappears and then you see the persistent object selection box with control handles (the thing I'm trying to customize).
See links:
http://fabricjs.com/customization
http://fabricjs.com/controls-customization
Ok here's a 2-part solution:
https://codepen.io/MarsAndBack/pen/bGExXzd
For the selection box stroke thickness:
Use fabric.Object.prototype.set to customize any object selection globally. Also, borderScaleFactor is documented, but not included in the fabric.js customization demos:
fabric.Object.prototype.set({
borderScaleFactor: 6
})
For the control handle stroke thickness:
Here we override differently, and actually draw new elements using standard HTML5 canvas properties. Through this method you could also target specific control handles and even use image icons.
fabric.Object.prototype._drawControl = controlHandles
fabric.Object.prototype.cornerSize = 20
function controlHandles (control, ctx, methodName, left, top) {
if (!this.isControlVisible(control)) {
return
}
var size = this.cornerSize
// Note 1: These are standard HTML5 canvas properties, not fabric.js.
// Note 2: Order matters, for instance putting stroke() before strokeStyle may result in undesired effects.
ctx.beginPath()
ctx.arc(left + size / 2, top + size / 2, size / 2, 0, 2 * Math.PI, false);
ctx.fillStyle = "pink"
ctx.fill()
ctx.lineWidth = 4 // This is the stroke thickness
ctx.strokeStyle = "red"
ctx.stroke()
}
SO code snippet:
const canvas = new fabric.Canvas("myCanvas")
canvas.backgroundColor="#222222"
this.box = new fabric.Rect ({
width: 240,
height: 100,
fill: '#fff28a',
myType: "box"
})
canvas.add(this.box)
this.box.center()
// Selection box border properties
// ----------------------------------------
fabric.Object.prototype.set({
borderColor: "white",
borderScaleFactor: 6
})
// Control handle properties
// ----------------------------------------
fabric.Object.prototype._drawControl = controlHandles
fabric.Object.prototype.cornerSize = 20
function controlHandles (control, ctx, methodName, left, top) {
if (!this.isControlVisible(control)) {
return
}
var size = this.cornerSize
// Note 1: These are standard HTML5 canvas properties, not fabric.js.
// Note 2: Order matters, for instance putting stroke() before strokeStyle may result in undesired effects.
ctx.beginPath()
ctx.arc(left + size/2, top + size/2, size/2, 0, 2 * Math.PI, false);
ctx.fillStyle = "pink"
ctx.fill()
ctx.lineWidth = 4
ctx.strokeStyle = "red"
ctx.stroke()
}
<script src="https://pagecdn.io/lib/fabric/3.6.3/fabric.min.js"></script>
<canvas id="myCanvas" width="700" height="400"></canvas>

How to find bit length of text with specific font and font size

I'm developing NativeScript JavaScript code to create dynamic text marker for maps. I have the code working that creates a marker for a specific string. My next step is to take any given string, determine its height and width in bits, and create the marker sized to contain the text.
My problem is finding the size of the text, given the text string itself, the font size, and the font family.
It looks like getMeasuredWidth could work, except that the string must already be loaded on a page before that function will return a value. In my case, I simply need to compute the size; the text won't otherwise appear as such on a page (the text in the marker becomes an image).
Is there a way to do this?
var bmp = BitmapFactory.create(200);
bmp.dispose(function (b) {
try {
b.drawRect(
"100,34", // size
'0,0', // upper-left coordinate
KnownColors.Black, // border color
KnownColors.Cornsilk // fill color
);
b.writeText(
"Parking",
"2,25",
{ color: KnownColors.Black, size: 8, name: 'fontawesome-webfont', });
...
In the code above, the width of "100" of the bounding rectangle actually represents the bit width of "Parking" with a small amount of padding. What I want to does calculate the rectangle's height and width and not hard-code it.
Try this, finding label size without adding it to Page upon button click
export function onFindButtonTap(args: EventData) {
const button = <any>args.object;
const label = new Label();
label.text = "Hello, found my size?"
label.fontSize = 20;
(<any>label)._setupAsRootView(button._context);
label.onLoaded();
label.measure(0, 0);
console.log(`Width : ${label.getMeasuredWidth()} x Height : ${label.getMeasuredHeight()}`);
}
Playground Sample
Note: I didn't get a chance to test it with iOS yet, let me know if you hit any issues.

kendo dialog window out of bounds at multiple uploads selected

I have an issue regarding a kendo dialog window including an upload.
When I upload multiple elements the list gets longer and longer and at some point gets bigger than my browserwindow and runs out of bounds at the bottom of the screen.
The insert button then is below the bottom bound of the browser but the browser doesn't allow me to scroll (firefox + chrome).
How can I limit my window to the browser screen and not exceed it?
#(Html.Kendo().Dialog()
.Name("ImageBrowser")
.Content( Html.Partial("ImageBrowserContent").ToString())
.MinWidth(400)
.MinHeight(800)
.MaxHeight(1000)
.MaxWidth(800)
.Modal(true)
.Visible(false)
)
#(Html.Kendo().Upload()
.Name("imageUpload")
.Messages(mess => mess.Select("Upload"))
.Async(a => a
.Save("Upload", "Image")
.Remove("RemoveUpload", "Image")
.AutoUpload(true)
)
)
I have provided a dojo here for you which hopefully is what you are after.
https://dojo.telerik.com/eqaZibIL
It uses the javascript version but you can just apply the function I have created to the dialog initial event. like so:
#Html.Kendo().Dialog().Events(e => e.InitOpen("dialog_resize"))
(This is some code I have modified for handling kendoWindow's so could be optimized more I think)
function dialog_resize() {
//THIS GETS THE POPUP DIALOG
var popUpDialog = $('#dialog').data("kendoDialog");
//THIS GETS THE CONTENT AREA FOR THE ENTIRE DIALOG
var contentArea = $(".k-widget.k-window.k-dialog");
//THIS GETS THE ACTUAL CONTENT AREA OF THE DIALOG IE.WHAT YOU WANT DISPLAYED
var innerForm = $("#dialog");
var windowHeight = $(window).innerHeight();
var windowWidth = $(window).innerWidth();
//CALCULATE THE WIDTH OF THE DIALOG AND SET IT TO 80%
//OF SCREEN REALESTATE TO STRECH OUT.
//NOT REQUIRED IF YOU ARE SETTING THE WIDTH MANUALLY.
contentArea.width(windowWidth * 0.8)
//CENTER THE DIALOG ON THE SCREEN.
popUpDialog.center();
//GET 97% OF THE AVAILABLE DIALOG CONTENT AREA TO SHOW Y-SCROLL BAR
var fixedHeight = (contentArea.height() * 0.97);
var fixedWidth = contentArea.width() * 0.965;
//SET THE HEIGHT, WIDTH AND SCROLL BAR OF THE CONTENT AREA
//SHOWING BLUE BORDER TO SHOW THE ITEM IS POSITIONING CORRECTLY IN DIALOG
innerForm.height(fixedHeight).width(fixedWidth).css({
maxHeight: fixedHeight + 'px !important',
maxWidth: fixedWidth + 'px !important',
overflowY: 'scroll',
overflowX: 'hidden',
border: '1px solid blue'
});
}
Hopefully you can follow what is going off here.
As long as you have set the maxHeight for the dialog on initialization all this seems to work correctly. I have applied a blue border to the content area just for demo purposes so you can see it in action.

Extendscript: How to check whether text content overflows the containing rectangle

I am using Extendscript for Photoshop CS5 to change the text of a text layer. Is there a way of checking whether the text fits e.g. by checking whether it overflows after changing the content?
I created a solution that works perfectly fine :). Maybe someone else can use it as well. Let me know if it works for you too!
function scaleTextToFitBox(textLayer) {
var fitInsideBoxDimensions = getLayerDimensions(textLayer);
while(fitInsideBoxDimensions.height < getRealTextLayerDimensions(textLayer).height) {
var fontSize = parseInt(textLayer.textItem.size);
textLayer.textItem.size = new UnitValue(fontSize * 0.95, "px");
}
}
function getRealTextLayerDimensions(textLayer) {
var textLayerCopy = textLayer.duplicate(activeDocument, ElementPlacement.INSIDE);
textLayerCopy.textItem.height = activeDocument.height;
textLayerCopy.rasterize(RasterizeType.TEXTCONTENTS);
var dimensions = getLayerDimensions(textLayerCopy);
textLayerCopy.remove();
return dimensions;
}
function getLayerDimensions(layer) {
return {
width: layer.bounds[2] - layer.bounds[0],
height: layer.bounds[3] - layer.bounds[1]
};
}
How to use / Explanation
Create a text layer that has a defined width and height.
You can change the text layers contents and then call scaleTextToFitBox(textLayer);
The function will change the text/font size until the text fits inside the box (so that no text is invisible)!
The script decreases the font size by 5% (* 0.95) each step until the texts fits inside the box. You can change the multiplier to achieve a more precise result or to increase performance.
I haven't found a way to do this directly. But I've used the following technique to determine the height I needed for a textbox (I wanted to keep the width constant) before.
expand the textbox's height well beyond what is needed to accommodate the text inside it.
duplicate the layer
rasterize the duplicate
measure the bounds of the rasterized layer.
adjust the bounds of the original text layer as needed
delete the rasterized duplicate
Totally roundabout - but it did work.

How to display vertical text (90 degree rotated) in all browsers?

How can I display vertical text (90 degree rotated) in all browsers?
(source: sun.com)
The problem is independent from the server side language. If it's not a problem when the vertically rendered text isn't text anymore but an image, choose the solution provided by tharkun. Otherwise, there are ways to do it in the presentation layer.
First, there's (at the moment) an IE-only solution, which is part of the CSS3 standard. You can check it live.
p {
writing-mode: tb-rl;
}
The CSS3 text module also specify some properties for text orientation.
Other guys do it with SVG.
I don't think you can rotate text with PHP/HTML/CSS. But you can create an image with GD containing vertical text.
Example:
header ("Content-type: image/png");
// imagecreate (x width, y width)
$img_handle = #imagecreatetruecolor (15, 220) or die ("Cannot Create image");
// ImageColorAllocate (image, red, green, blue)
$back_color = ImageColorAllocate ($img_handle, 0, 0, 0);
$txt_color = ImageColorAllocate ($img_handle, 255, 255, 255);
ImageStringUp ($img_handle, 2, 1, 215, $_GET['text'], $txt_color);
ImagePng ($img_handle);
ImageDestroy($img_handle);
function verticletext($string)
{
$tlen = strlen($string);
for($i=0;$i<$tlen;$i++)
{
$vtext .= substr($string,$i,1)."<br />";
}
return $vtext;
}
there you go no echo
Text rotation is also possible with other browsers.
CSS:
/*Safari*/
-webkit-transform: rotate(-90deg);
/*Firefox*/
-moz-transform: rotate(-90deg);
/*Opera*/
-o-transform: rotate(-90deg);
/*IE*/
writing-mode: tb-rl;
filter: flipV flipH;
I use the function below if table header rows are too long. It's quite useful because it's easy to use, fast and you don't have to calculate text height & width. Those css-gimmicks just don't work.
#######################################################
# convert text to image and embed it to html
# uses /tmp as a cache to make it faster
# usage: print imagetext("Hello my friend");
# Created by Ville Jungman, GPL-licenced, donated by www.varuste.net
function imagetext($text,$size = 10,$color = array(253,128,46)){
$dir = "/tmp/tekstit";
$filename = "$dir/" . base64_encode($text);
if(!file_exists($filename)){
$font = "/usr/share/fonts/truetype/freefont/FreeSans.ttf";
$box = imagettfbbox($size,90,$font,$text);
$w = -$box[4] - 1;
$h = -$box[3];
$im = imagecreatetruecolor($w,$h);
$white = imagecolorallocate($im,$color[1],$color[2],$color[3]);
$black = imagecolorallocate($im, 0x00, 0x00, 0x00);
imagecolortransparent($im,$white);
imagefilledrectangle($im, 0, 0, $size, 99, $white);
imagettftext($im,$size,90,$size,$h,$black,$font,$text);
#mkdir($dir);
imagepng($im,$filename);
imagedestroy($im);
}
$data = base64_encode(file_get_contents($filename));
return "<img src='data:image/png;base64,$data'>";
}
This thread suggests that you can write text to an image and then rotate the image.
It appears to be possible with IE but not with other browsers so it might be one of those little win for IE6 =)
imagettftext oughta do the trick.
As far as I know it's not possible to get vertical text with CSS, so that means that the rotated text has to be in an image. It's very straightforward to generate with PHP's' libgd interface to output an image file.
Note however that this means using one script to produce the image, and another to produce the surrounding web page. You can't generally (inline data: URI's notwithstanding) have one script produce more than one page component.
Use raphaeljs
It works on IE 6 also
http://raphaeljs.com/text-rotation.html
function verticletext($string)
{
$tlen = strlen($string);
for($i=0;$i<$tlen;$i++)
{
echo substr($string,$i,1)."<br />";
}
}

Resources