phaser/src/gameobjects/text/GetTextSize.js

77 lines
1.9 KiB
JavaScript
Raw Normal View History

2018-02-12 16:01:20 +00:00
/**
* @author Richard Davey <rich@photonstorm.com>
* @copyright 2018 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
2018-02-07 02:46:11 +00:00
/**
* Returns an object containing dimensions of the Text object.
2018-03-16 17:29:39 +00:00
*
* @function Phaser.GameObjects.Text.GetTextSize
* @since 3.0.0
*
* @param {Phaser.GameObjects.Text} text - The Text object to calculate the size from.
* @param {BitmapTextMetrics} size - The Text metrics to use when calculating the size.
* @param {array} lines - The lines of text to calculate the size from.
2018-03-16 17:29:39 +00:00
*
* @return {object} An object containing dimensions of the Text object.
2018-02-07 02:46:11 +00:00
*/
var GetTextSize = function (text, size, lines)
{
var canvas = text.canvas;
var context = text.context;
var style = text.style;
var lineWidths = [];
var maxLineWidth = 0;
var drawnLines = lines.length;
if (style.maxLines > 0 && style.maxLines < lines.length)
{
drawnLines = style.maxLines;
}
style.syncFont(canvas, context);
// Text Width
for (var i = 0; i < drawnLines; i++)
{
var lineWidth = style.strokeThickness;
lineWidth += context.measureText(lines[i]).width;
// Adjust for wrapped text
if (style.wordWrap)
{
lineWidth -= context.measureText(' ').width;
}
lineWidths[i] = Math.ceil(lineWidth);
maxLineWidth = Math.max(maxLineWidth, lineWidths[i]);
}
// Text Height
var lineHeight = size.fontSize + style.strokeThickness;
var height = lineHeight * drawnLines;
var lineSpacing = text.lineSpacing;
2017-04-26 14:34:15 +00:00
// Adjust for line spacing
if (lines.length > 1)
{
height += lineSpacing * (lines.length - 1);
}
2017-04-26 14:34:15 +00:00
return {
width: maxLineWidth,
height: height,
lines: drawnLines,
lineWidths: lineWidths,
lineSpacing: lineSpacing,
lineHeight: lineHeight
};
};
module.exports = GetTextSize;