Khairu Aqsara
Khairu Aqsara

Reputation: 1310

Two colors in one text field using Actionscript 3

Is it possible to have two text colors in one text field using Actionscript 3.0?

ex: how can i make like the first string black and the second string red?

Here is my code when using a single color:

    public function logs(txt)
    {
        if (txt == '')
        {
            textLog.text = "Let's Open up our treasure boxes !!!";
        }
        else
        {
            textLog.text = '' + txt + '';
        }
        textLog.x = 38.60;
        textLog.y = 60.45;
        textLog.width = 354.50;
        textLog.height = 31.35;
        textLog.selectable = false;
        textLog.border = false;
        var format:TextFormat = new TextFormat();
        var myFont:Font = new Font1();
        format.color = 0x000000;
        format.font = myFont.fontName;
        format.size = 18;
        format.align = TextFormatAlign.CENTER;
        format.bold = false;
        textLog.embedFonts = true;
        textLog.setTextFormat(format);
        this.addChild(textLog);
    }

Upvotes: 11

Views: 12524

Answers (2)

Leonardo Martiniano
Leonardo Martiniano

Reputation: 1

If you want to do like that, you need create a function to control. charAt(DEFINE INDEX OF STRING HERE).

    var format2:TextFormat = textbox.defaultTextFormat;
    format2.color = 0x000000;
    textbox.defaultTextFormat = format2;

    if((textbox.text.charAt(3) == "d") && ( textbox.text.charAt(4) == "i")){            
        var format1:TextFormat = textbox.defaultTextFormat;
        format1.color = 0xFF0000;
        textbox.setTextFormat(format1, 3, 5);}
    else{
        textbox.setTextFormat(textbox.defaultTextFormat);}

Upvotes: 0

Diode
Diode

Reputation: 25135

In setTextFormat you can specify start index and end index. You can also render text as html using textLog.htmlText.

First set the text

var t:TextField  = new TextField();
t.text = "BLUEGREEN";
addChild(t);

Then method 1

var format1:TextFormat = t.getTextFormat(0, 4);
format1.color = 0x0000ff;
t.setTextFormat(format1, 0, 4);


var format2:TextFormat = t.getTextFormat(5, t.length);
format2.color = 0x00ff00;
t.setTextFormat(format2, 5, t.length);

Or method 2

t.htmlText = '<font color="#0000ff">BLUE</font><font color="#00ff00">GREEN</font>';

Upvotes: 17

Related Questions