Flex 4 TextFlow のアンカー装飾

2012.02.07

この記事は公開されてから1年以上経過しています。情報が古い可能性がありますので、ご注意ください。

日々のお仕事シリーズ(仮称)

Flex 4 の RichEditableText コンポーネントは、内部で TLF(Text Layout Framework) を使用しています。

そして、この TLF では、テキストコンテンツを管理する役割を果たす TextFlow というクラスのオブジェクトを使用して、文字装飾を実現しますが、あまり使う機会がないためか、お作法を都度忘れてしまうので ( 特にアンカーの装飾 )、サンプルコードを残しておくことにしました。

実装コード (Main.mxml)

<?xml version="1.0" encoding="utf-8"?>
<s:Application
xmlns:fx = "http://ns.adobe.com/mxml/2009"
xmlns:s  = "library://ns.adobe.com/flex/spark"
>
<fx:Script>
<![CDATA[
    import flashx.textLayout.events.FlowElementMouseEvent;
    import flashx.textLayout.formats.TextLayoutFormat;
    protected var linkNormalFormat :TextLayoutFormat;
    protected var linkHoverFormat  :TextLayoutFormat;
    protected var linkActiveFormat :TextLayoutFormat;
    protected override function createChildren():void {
        super.createChildren();
        tf.addEventListener("任意の文字列", anchorClickHandler);

        linkNormalFormat = new TextLayoutFormat();
        linkNormalFormat.color = 0x990000;
        linkNormalFormat.textDecoration = "none";

        linkHoverFormat  = new TextLayoutFormat();
        linkHoverFormat.color = 0xcc0000;
        linkHoverFormat.textDecoration = "underline";

        linkActiveFormat = new TextLayoutFormat();
        linkActiveFormat.color = 0x000099;

        tf.linkNormalFormat = linkNormalFormat;
        tf.linkHoverFormat  = linkHoverFormat;
        tf.linkActiveFormat = linkActiveFormat;
    }
    protected function anchorClickHandler(event:FlowElementMouseEvent):void {
        ta.appendText(event.flowElement.getText() + "\n");
    }
]]>
</fx:Script>

<s:VGroup width="50%" height="50%" verticalCenter="0" horizontalCenter="0">
    <s:RichEditableText id="ret" fontSize="40" editable="false" selectable="false" width="100%" height="100%">
        <s:textFlow>
            <s:TextFlow id="tf">
                <s:p><s:a href="event:任意の文字列">たいが</s:a>さん、困っ<s:a href="event:任意の文字列">taiga</s:a></s:p>
            </s:TextFlow>
        </s:textFlow>
    </s:RichEditableText>
    <s:TextArea id="ta" width="100%" height="100%" />
</s:VGroup>

</s:Application>

解説

TextFlow オブジェクトには、linkNormalFormat、 linkHoverFormat、 linkActiveFormatという 3 つのアンカー装飾用のプロパティがあり、これらに対して、TextLayoutFormat オブジェクトをセットします。

TextLayoutFormat の詳細はヘルプを見てください ( http://help.adobe.com/ja_JP/FlashPlatform/reference/actionscript/3/flashx/textLayout/formats/TextLayoutFormat.html )

ちなみに、TextFlow で使用する タグ ( LinkElement オブジェクト ) の href プロパティでは、"event:≪任意の文字列≫" という値をセットすることで、≪任意の文字列≫のイベントをハンドリングすることが可能になります。

出力結果

出力結果は次の通り

[SWF]http://public-blog-dev.s3.amazonaws.com/wp-content/uploads/2012/02/AnchorSample20120207.swf,640,480[/SWF]