2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

CreareJSのTextで指定した幅で自動折り返しした複数行テキストを返す関数(日本語対応)

Last updated at Posted at 2013-11-14

EaselJS(0.6.1で確認)においてTextに日本語を指定すると、lineWidthが効かず改行されません。
これはこの問題を解決するための関数です。(Haxeコードです)

hoge.hx
import createjs.easeljs.Text;
class Main {
	//指定した幅(lineWidth)で自動折り返しした複数行テキストを返す
	public static function wrapText(text:Text, lineWidth:Int):String {
		text.lineWidth = null;
		
		var str = text.text;
		var newStr:String = "";
		var r:EReg = new EReg("[\r\n]+|[\n]+|[\n]+", "g");
		var lines:Array<String> = r.split(str);
		
		var line:String;
		var words:Array<String>;
		var oneLineStr:String;
		var len:Int = lines.length;
		for (i in 0...len) {
			line = lines[i];
			text.text = line;
			if (text.getMeasuredWidth() < lineWidth ) {
				newStr += line;
				if(i < len-1) newStr += "\n";
				continue;
			}
			
			words = line.split("");//一文字ごとに分割する
			oneLineStr = "";
			for (w in words) {
				text.text = oneLineStr + w;
				if (text.getMeasuredWidth() > lineWidth ) {
					newStr += oneLineStr + "\n";
					oneLineStr = "";
				}
				oneLineStr += w;
			}
			newStr += oneLineStr;
			if(i < len-1) newStr += "\n";
		}
		
		text.text = newStr;
		
		return newStr;
	}
}
2
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?