浏览代码

added support for various line breaking chars (not only space)

ncannasse 12 年之前
父节点
当前提交
e87fe7dca5
共有 2 个文件被更改,包括 29 次插入19 次删除
  1. 15 1
      h2d/Font.hx
  2. 14 18
      h2d/Text.hx

+ 15 - 1
h2d/Font.hx

@@ -53,7 +53,21 @@ class Font #if !macro extends Tile #end {
 	public function hasChar( code : Int ) {
 		return glyphs[code] != null;
 	}
+
+	public function isSpace(code) {
+		return code == ' '.code || code == 0x3000;
+	}
 	
+	public function isBreakChar(code) {
+		return switch( code ) {
+		case ' '.code, 0x3000: true;
+		case '!'.code, '?'.code, '.'.code, ','.code, ':'.code: true;
+		case '!'.code, '?'.code, '.'.code, ','.code, ':'.code: true; // full width
+		case '・'.code, '、'.code, '。'.code: true; // JP
+		default: false;
+		}
+	}
+		
 	function init() {
 		lineHeight = 0;
 		var tf = new flash.text.TextField();
@@ -158,7 +172,7 @@ class Font #if !macro extends Tile #end {
 		bmp.dispose();
 		
 		inline function map(code, to) {
-			if( glyphs[code] == null ) glyphs[code] = glyphs[to];
+			if( glyphs[code] == null ) glyphs[code] = glyphs[to] else if( glyphs[to] == null ) glyphs[to] = glyphs[code];
 		}
 		// fullwidth unicode to ASCII (if missing)
 		for( i in 1...0x5E )

+ 14 - 18
h2d/Text.hx

@@ -60,11 +60,7 @@ class Text extends Drawable {
 	public function calcTextWidth( text : String ) {
 		return initGlyphs(text,false).width;
 	}
-	
-	function isSpace(code) {
-		return code == ' '.code || code == 0x3000;
-	}
-	
+
 	function initGlyphs( text : String, rebuild = true ) {
 		if( rebuild ) glyphs.reset();
 		var letters = font.glyphs;
@@ -72,31 +68,31 @@ class Text extends Drawable {
 		for( i in 0...text.length ) {
 			var cc = text.charCodeAt(i);
 			var e = letters[cc];
+			var newline = cc == '\n'.code;
 			// if the next word goes past the max width, change it into a newline
-			if( isSpace(cc) && maxWidth != null ) {
+			if( font.isBreakChar(cc) && maxWidth != null ) {
 				var size = x + e.width + 1;
 				var k = i + 1, max = text.length;
 				while( size <= maxWidth ) {
 					var cc = text.charCodeAt(k++);
-					if( cc == null || isSpace(cc) || cc == '\n'.code ) break;
+					if( cc == null || font.isSpace(cc) || cc == '\n'.code ) break;
 					var e = letters[cc];
 					if( e != null ) size += e.width + 1;
 				}
 				if( size > maxWidth ) {
-					e = null;
-					cc = '\n'.code;
+					newline = true;
+					if( font.isSpace(cc) ) e = null;
 				}
 			}
-			if( e == null ) {
-				if( cc == '\n'.code ) {
-					if( x > xMax ) xMax = x;
-					x = 0;
-					y += font.lineHeight;
-				}
-				continue;
+			if( e != null ) {
+				if( rebuild ) glyphs.add(x, y, e);
+				x += e.width + 1;
+			}
+			if( newline ) {
+				if( x > xMax ) xMax = x;
+				x = 0;
+				y += font.lineHeight;
 			}
-			if( rebuild ) glyphs.add(x, y, e);
-			x += e.width + 1;
 		}
 		return { width : x > xMax ? x : xMax, height : x > 0 ? y + font.lineHeight : y };
 	}