flash on 2014-5-30

by bkzen
t260 

TextFormat の罠
@author jc at bk-zen
♥0 | Line 49 | Modified 2014-05-30 12:43:58 | MIT License
play

ActionScript3 source code

/**
 * Copyright bkzen ( http://wonderfl.net/user/bkzen )
 * MIT License ( http://www.opensource.org/licenses/mit-license.php )
 * Downloaded from: http://wonderfl.net/c/7S0Y
 */

package //t260 
{
    import flash.display.Sprite;
    import flash.events.Event;
    import flash.events.MouseEvent;
    import flash.text.TextField;
    import flash.text.TextFormat;
    
    /**
     * TextFormat の罠
     * @author jc at bk-zen
     */
    [SWF (backgroundColor = "0xFFFFFF", frameRate = "30", width = "465", height = "465")]
    public class Test240 extends Sprite
    {
        private static const MESSAGE: String = "0123456789\n9876543210\n3だけボールドにしようとしたのに\nなぜか3の後ろもボールドになる\n改行すると直る。";
        private static const FONT: String = "_sans";
        
        private var textField: TextField = new TextField();
        private var normal: TextFormat = new TextFormat(FONT, 17, 0x555555); // 引数を省略するとこうなる。フォントカラーなども同じ。
        private var bold: TextFormat = new TextFormat(FONT, 17, 0x555555, true);
        private var index: int;
        
        public function Test240() 
        {
            textField.autoSize = "left";
            addChild(textField);
            addEventListener(Event.ENTER_FRAME, loop);
            stage.addEventListener(MouseEvent.CLICK, reset);
        }
        
        private function loop(e: Event): void 
        {
            var char: String = MESSAGE.substr(index, 1);
            textField.appendText(char);
            if (char == "3")
            {
                textField.setTextFormat(bold, index);
            }
            else 
            {
                textField.setTextFormat(normal, index);
            }
            if (++index >= MESSAGE.length)
            {
                removeEventListener(Event.ENTER_FRAME, loop);
            }
        }
        
        private function reset(e:MouseEvent):void 
        {
            textField.text = "";
            index = 0;
            normal.bold = normal.bold == null ? false : null;
            addEventListener(Event.ENTER_FRAME, loop);
        }
    }
}