Skip to content

Instantly share code, notes, and snippets.

@jessefreeman
Last active December 13, 2015 23:38
Show Gist options
  • Save jessefreeman/4992664 to your computer and use it in GitHub Desktop.
Save jessefreeman/4992664 to your computer and use it in GitHub Desktop.
/**
* A TextureAtlasFont extends Impact's Font class to allow looking up a font's bitmap from the TexturePacker JSON array
*
* Author: @jessefreeman
*
* Version 0.1 - 2013/02/19
*
* Usage:
* DemoTextureAtlasFont = ig.Game.extend({
* textureImage: new ig.Image('media/font.png'),
* init: function ()
* {
* this.textureAtlas = new ig.TextureAtlas(this.textureImage, new ig.PackedTextures().font); // Create the texture atlas
* this.textureFont = new ig.TextureAtlasFont(this.textureAtlas);
* },
* draw: function ()
* {
* this.parent();
* this.textureFont.draw("Hello World", 0, 0);
* }
* })
*
* Notes:
* This is based off of textures generated by ShoeBox. Use the following templates:
* Format Loop: \t{\n\t\t"filename": "@id",\n\t\t"frame": {"x":@x,"y":@y,"w":@w,"h":@h,"sx":@sx,"sy":@sy,"advanceX":@advanceX,"advanceY":@advanceX,}},\n
* Format Outer: {"frames": [\n@loop]\n,"meta": {\n\t"app": "ShoeBox",\n\t"lineHeight":@advanceY,\n\t"kerning":@kerning,\n\t"spaceWidth:0,\n\t"size": {"w":@texW,"h":@texH}\n}\n}
*/
ig.TextureAtlasFont = ig.Font.extend({
textureAtlas: null,
spaceWidth: 0,
init: function (textureAtlas, kerning, spaceWidth)
{
this.textureAtlas = textureAtlas;
this.height = this.textureAtlas.packedTexture.meta.lineHeight;
this.letterSpacing = (typeof kerning == "undefined") ? this.textureAtlas.packedTexture.meta.kerning : kerning;
this.spaceWidth = (typeof spaceWidth == "undefined") ? this.textureAtlas.packedTexture.meta.spaceWidth : spaceWidth;
if (typeof this.spaceWidth == "undefined")
this.spaceWidth = 0;
},
_drawChar: function (c, targetX, targetY)
{
if (c == 0)
return this.spaceWidth + this.letterSpacing;
var frameData = this.textureAtlas.getFrameData(c + this.firstChar);
this.textureAtlas.image.draw(targetX + frameData.frame.sx, targetY + frameData.frame.sy, frameData.frame.x, frameData.frame.y, frameData.frame.w, frameData.frame.h);
return frameData.frame.w + this.letterSpacing;
},
_widthForLine: function (text) {
var width = 0;
var frameData;
var charW = 0;
for (var i = 0; i < text.length; i++) {
if (text.charCodeAt(i) == 0)
charW = this.spaceWidth + this.letterSpacing;
else {
charW = this.textureAtlas.getFrameData(text.charCodeAt(i)).frame.w + this.letterSpacing;
}
width += charW;
}
return width;
},
});
@jessefreeman
Copy link
Author

This is based on https://github.com/dpweberza/ImpactJS-Plugins and is a replacement for the supplied TextureAtlasFont class.

@jessefreeman
Copy link
Author

Updated with replacement for _widthForLine calculation.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment