Skip to content

Instantly share code, notes, and snippets.

@alumican
Last active December 11, 2015 17:19
Show Gist options
  • Save alumican/4634109 to your computer and use it in GitHub Desktop.
Save alumican/4634109 to your computer and use it in GitHub Desktop.
FlashのTextField内の特定文字列を指定したフォントに置換するスクリプト
/**
* TextField内のアスキー文字列(半角英数記号)を指定のフォントに置換する
* @param field 操作対象のTextField
* @param font 置換後のフォント
*/
function replaceAsciiFont(tf:TextField, font:String):void
{
replaceFont(tf, /[\u0020-\u007e]+/g, font);
}
/**
* TextField内の特定文字列を指定のフォントに置換する
* @param field 操作対象のTextField
* @param pattern 置換対象にマッチする正規表現
* @param font 置換後のフォント
*/
function replaceFont(tf:TextField, pattern:RegExp, font:String):void
{
var fmt:TextFormat = new TextFormat(font), idx:int;
function callback(index:int, result:Object):void {
idx = result.index;
tf.setTextFormat(fmt, idx, idx + result[0].length);
}
find(tf.text, pattern, callback);
}
/**
* 文字列の中から正規表現に一致した部分文字列を見つける
* @param source 検索対象の文字列
* @param pattern 検索正規表現
* @param callback 一致するごとに実行する関数。引数は順番に、マッチした順:int, RegExp.execの結果:Object
* @return マッチした部分文字列の開始インデックス
*/
function find(source:String, pattern:RegExp, callback:Function = null):Array
{
var indices:Array = new Array(), result:Object, i:int = -1;
while (result = pattern.exec(source)) {
if (callback != null) callback.call(null, ++i, result);
indices.push(result.index);
if (!pattern.global) break;
}
return indices;
}
/**
* テストコード
* 各種フォントはあらかじめ埋め込んでおく
*/
var tf:TextField = TextField(addChild(new TextField()));
var fmt:TextFormat = new TextFormat("ヒラギノ角ゴ Pro W3", 18);
tf.defaultTextFormat = fmt;
tf.wordWrap = true;
tf.width = 500;
tf.height = 300;
tf.text = "PC市場の低迷に対応すべく、Acerが「eMachines」ブランドの製品開発を中止し、「Gateway」および「Packard Bell」ブランドに再び照準を合わせて、“PCを超える”新製品を提供しようともくろんでいる。(Computerworld)";
//英数記号のみHelveticaに置き換える
replaceAsciiFont(tf, "Helvetica 65 Medium");
@alumican
Copy link
Author

//おまけ
//TextFormat.fontに指定するときの名称を列挙する(インストール済みフォントのみ)
var fonts = Font.enumerateFonts(true);
fonts.sortOn("fontName", Array.CASEINSENSITIVE);
for each(var f:Font in fonts) trace(f.fontName);

@psyark
Copy link

psyark commented Jan 25, 2013

// Twitterで書いたreplaceのコールバックでなんとかするやつ(汚かった)
fmt.color = 0xFF0000;
var index:int = 0;
tf.text.replace(/\G(.*?)[\u0020-\u007e]+/gs, function (match:String, group1:String, pos:int, source:String):void {
tf.setTextFormat(fmt, index + group1.length, index + match.length);
index += match.length;
});

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