Impact

This forum is read only and just serves as an archive. If you have any questions, please post them on github.com/phoboslab/impact

1 decade ago by Kingsley

I needed to wrap some text so it fitted into a box shape rather than running all the way across the screen. This is the solution I came up with:

WordWrap = ig.Class.extend({

    text:"",
    maxWidth:100,
    cut: false,

    init:function (text, maxWidth, cut) {
        this.text = text;
        this.maxWidth = maxWidth;
        this.cut = cut;
    },

    wrap:function(){
        var regex = '.{1,' +this.maxWidth+ '}(\\s|$)' + (this.cut ? '|.{' +this.maxWidth+ '}|.+$' : '|\\S+?(\\s|$)');
        return this.text.match( RegExp(regex, 'g') ).join( '\n' );
    }

});

var wrapper = new WordWrap('some length text',25);
wrapper.wrap();


You basically supply the text, the max length and optionally a boolean for the cut option which is false by default. Cut just means instead of wrapping by word it will split the word up and wrap by char. But I guess most of the time wrapping by word is more readable.

1 decade ago by alexandre

Nicely done. Added to my codebox. Thanks!

1 decade ago by ShawnSwander

Although this is probably the best example posted for solving this issue I know of it seems like a better one is possible as the font file can be read with each character's length in pixels rather than assuming each character is the longest possible letter in the font. There can be quite a difference between a period on a small font being 1 pixel and a w being like 9 pixels with a 1 pixel buffer between letters we're looking at 2 to 10 difference so the word might wrap when its only 20% finished with the line right?
I could be misunderstanding your code if it actually detects the width of different characters.

Is there code to read the font png file?

1 decade ago by Arantor

There is very definitely code to read the PNG file - Impact does this itself in order to be able to align the text centrally. Take a look in the font.js file to see what it's doing.

1 decade ago by ShawnSwander

this is my exact code it could be simplified for more universal use.
the .wrap substring just holds the position since the last wrap (new line). textype is the string being wrapped. anyway .widthForString is the function you should look up for this.
if (ig.game.font.widthForString(ig.game.chathud.texttype.substring(ig.game.chathud.wrap, 255))>300){
			ig.game.chathud.wrap = ig.game.chathud.texttype.lastIndexOf(' ');
			ig.game.chathud.texttype  = ig.game.chathud.texttype.substring(0, ig.game.chathud.wrap)+"\n"+ig.game.chathud.texttype.substring(ig.game.chathud.wrap, 255);
		}	

This seemed simpler
Page 1 of 1
« first « previous next › last »