Home > AS3 > [AS3] TextFieldのTextFormatを部分的に変えたいの続き

[AS3] TextFieldのTextFormatを部分的に変えたいの続き

TextFieldのTextFormatを部分的に変えれることがわかったので、
簡単なリッチテキストエディタ的なものを作ってみました。

selectionBeginIndexselectionEndIndexを使用するとテキストエリアの選択範囲を取得できるんです。
なので、テキストの選択されてる範囲のフォーマットを変更!とかができるんです。

caretIndexプロパティでもカーソル位置を取得できるんです。
でもって、ヘルプに

テキストが選択されていない場合、このプロパティは caretIndex の値になります。


ってあるんで、最初はcaretIndexとselectionBeginIndexが一緒だったら選択されてないってしてました。
んがっ、文章の後ろから前に向かって選択した場合、caretIndexとselectionBeginIndexが一緒になっちゃうんです。
caretIndexとselectionBeginIndexが一緒でも選択されてる場合があるんです!
なんで、selectionBeginIndex、selectionEndIndexが一緒の場合は選択範囲なし!って判断するようにしました。

選択範囲のテキストを太字にしたり、しなかったりの例

// 太字ボタンにイベントリスナー登録
boldButton.addEventListener( MouseEvent.CLICK, boldClick );

/*
* 太字ボタン押下時処理
*/
function boldClick( e:Event ){
    // 選択されてない場合は処理しない
    if( inputText.selectionEndIndex == inputText.selectionBeginIndex) return;


    // 選択範囲のTextFormatを取得
    var fmt:TextFormat = inputText.getTextFormat( inputText.selectionBeginIndex, inputText.selectionEndIndex );
    // 選択範囲の太字プロパティを変更
    fmt.bold = !fmt.bold;
    // 選択範囲にテキストフォーマットを適用
    inputText.setTextFormat( fmt,inputText.selectionBeginIndex, inputText.selectionEndIndex );
}



で、これができたらこのTextFormatを保存したくなってくるのが人の情ってもんです。
でも、これができないんですicon:face_shock

// こうやって一気に取得するとだめ
inputText.getTextFormat();



なんで、1文字ずつ取得して保存する。。。っていうアナログ方式で対応しました。

/*
* 1文字ずつTextFormatを保存する
*/
function onSaveBtn( e:Event ){
    // 適当にSharedObject
    var so:SharedObject = SharedObject.getLocal("font-sample");
    // textFormatの配列
    var fontFormat:Array = new Array();
    for( var i = 0; i < inputText.length; i++){
        var fontInfo:Object = new Object();
        var fmt:TextFormat = inputText.getTextFormat(i , i + 1)
        fontInfo.bold = fmt.bold;
        fontInfo.color = fmt.color;
        fontInfo.underline = fmt.underline;
        fontInfo.italic = fmt.italic;

        fontFormat.push( fontInfo );
    }
    
    so.data.format = fontFormat;
    so.data.memo = inputText.text;
    so.flush();
}



で、こんな感じのことをやってできたやつです。
他にもフォントとかサイズとかも変えたりします。

トラックバック : http://cocoasaurus.com/mt/mt-tb.cgi/176

コメント:0

コメント

Home > AS3 > [AS3] TextFieldのTextFormatを部分的に変えたいの続き

↑page top