ActionScript 3.0 function for modify TextField - actionscript-3

I started one week ago to study ActionScript 3.0. I would like to do a simple game. It will start with a window displaying a welcome message( "press the button to start"), and a arrow that start from the text and point to the button. I want to create everything from code. I'm using a TextField for the welcome message but I have some trouble. I created a file .fla AIR for Destkop. Then I associated to that file a class called mainFunzioneModidificaTest.as . In this class I wrote a function to set the text of the first window. I use the TextFormat but when I run the .fla file I see the text but without any formatting.The color, the dimension and the font dosen't change Here is the code. Can someone help me? Thank you!
package {
import flash.display.MovieClip;
import flash.text.TextField;
import flash.text.TextFormat;
public class mainFunzioneModificaTest extends MovieClip {
public function mainFunzioneModificaTest() {
setText();
}
function setText(): void {
var text: TextField = new TextField();
var myFormat: TextFormat = new TextFormat("Arial", 39, 0xFF0000);
text.setTextFormat(myFormat);
text.text = "Hello";
addChild(text);
}
}
}

You need to set the text first before calling setTextFormat(), or alternatively use text.defaultTextFormat = myFormat;
From the TextFormat documentation:
Use the TextField.defaultTextFormat property to apply formatting BEFORE you add text to the TextField, and the setTextFormat() method to add formatting AFTER you add text to the TextField
Set text before calling setTextFormat():
function setText(): void {
var text: TextField = new TextField();
var myFormat: TextFormat = new TextFormat("Arial", 39, 0xFF0000);
text.text = "Hello";
text.setTextFormat(myFormat);
addChild(text);
}
or set defaultTextFormat:
function setText(): void {
var text: TextField = new TextField();
var myFormat: TextFormat = new TextFormat("Arial", 39, 0xFF0000);
text.defaultTextFormat = myFormat;
text.text = "Hello";
addChild(text);
}

Related

Dynamically display text in Flex, ActionScript 3

I've been having problems displaying text in ActionScript 3 using Flex SDK 4.6. Any method I try results in no change or a black screen; here is my project code and attempts.
MyProject.mxml is simply and mx:Application tag with the relevant parts being
<mx:Script>
<![CDATA[
include "MyProject.as"; //simply running my project file
]]>
</mx:Script>
and
<mx:Canvas id="gamePanel" x="0" y="0" width="100%" height="100%"/> //defining the canvas
In MyProject.as I have
import flash.display.*;
import flash.events.*;
import mx.events.*;
import mx.controls.*;
import Game;
public static const SCREEN_WIDTH:int = 960;
public static const SCREEN_HEIGHT:int = 720;
private var initializationCompleted:Boolean = false;
public var screenBuffer:BitmapData;
public var game:Game;
public function setup():void {
screenBuffer = new BitmapData(SCREEN_WIDTH, SCREEN_HEIGHT, false, 0x00000000);
game = new Game(SCREEN_WIDTH, SCREEN_HEIGHT, screenBuffer);
initializationCompleted = true;
}
private function updateFrame():void {
if (!initializationCompleted) {
return;
}
draw();
gamePanel.graphics.clear();
gamePanel.graphics.beginBitmapFill(screenBuffer, null, false, false);
gamePanel.graphics.drawRect(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
gamePanel.graphics.endFill();
}
private function draw():void {
game.update();
}
And in Game.as, I simply draw everything using the BitmapData class, and then copy everything to the screenBuffer:
screenBuffer.copyPixels(myBitmap, new Rectangle(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT), new Point(0,0));
(This is only the relevant code - I trimmed as much as possible to leave a "Minimal, Complete, and Verifiable example")
Now I have been having problems displaying text in my project. I know that TextField is a subclass of flash.display.Sprite which can be added to the canvas. Whenever I try using something like
var txtHello:TextField = new TextField();
txtHello.text = "Hello World";
gamePanel.addChild(txtHello)
this either changes nothing (if used in setup(), I'm assuming I'm drawing over it or else it is never displayed) or causes a black screen (if used anywhere in updateFrame(), I'm assuming I'm creating infinite sprites).
I have tried instead, creating a new file named "TextWithImage.as" with the contents
//this is ripped off the adobe help page
package {
import flash.display.Sprite;
import flash.text.*;
public class TextWithImage extends Sprite {
private var myTextBox:TextField = new TextField();
private var myText:String = "Hello World";
public function TextWithImage() {
addChild(myTextBox);
myTextBox.text = myText;
}
}
}
importing it in MyProject.as, and then using it as
gamePanel.addChild(new TextWithImage());
to the same effect as my previous attempt.
What is the simplest way to display text in Flex/AS3? Any help is appreciated, and thank you in advance!
There's a trick. Flex components, albeit having the same addChild method derived from DisplayObjectContainer class, cannot actually add regular Flash content - Shape, Sprite, MovieClip, TextField, Bitmap - directly. More to that, they don't produce any runtime error, which I personally think they totally could to not confuse new people.
Flex component can only addChild classes that extend the basic UIComponent class. At the same time, UIComponent can addChild regular Flash content. Thus you do it as following:
var proxyContainer:UIComponent = new UIComponent;
var txtHello:TextField = new TextField;
txtHello.text = "Hello World";
proxyContainer.addChild(txtHello);
gamePanel.addChild(proxyContainer);

Check if font is embedded?

Can I check if I'm using an actual font when I create TextFormat/TextField ? If I specify a not embedded font or use any random string, no text is displayed and I don't know why.
import flash.display.Sprite;
import flash.text.TextField;
import flash.text.TextFieldAutoSize;
import flash.text.TextFormat;
public class SimpleSprite extends Sprite
{
//[Embed(source="C:/Windows/Fonts/Arial.ttf",fontName="default_font",mimeType="application/x-font",fontWeight="normal",fontStyle="normal",advancedAntiAliasing="true",embedAsCFF="false")]
//private static var defaultFont: String;
public function SimpleSprite()
{
var t: TextField = new TextField;
t.autoSize = TextFieldAutoSize.LEFT;
t.defaultTextFormat = new TextFormat("default_font", 16, 0xff0000);
t.embedFonts = true;
t.text = "hello world";
addChild(t);
}
}
It doesn't display any text when the embed lines are missing.
Important: My package that creates TextFields does not embed anything and I wish to keep it that way. The embedding must be done by the programmer who uses the package. I want to check if the font is embedded and throw an error if not.
You can use Font.enumerateFonts which will return an array of available embedded fonts. You could use that to create a function like the following:
private function hasEmbeddedFont(fontName:String):Boolean
{
var fonts:Array = Font.enumerateFonts();
for each(var font:Font in fonts)
{
if (font.fontName == fontName)
{
return true;
}
}
return false;
}
And then use it something like this:
t.autoSize = TextFieldAutoSize.LEFT;
t.defaultTextFormat = new TextFormat("default_font", 16, 0xff0000);
t.embedFonts = hasEmbeddedFont("default_font");
t.text = "hello world";
If you're building a library for others to use, you might consider abstracting it into your own custom subclass of TextField so it's all handled automatically.

how to write on screen in AS3

So I am creating a module and I have a screen that I need to be able to allow the users to write questions that they have on their screens in a text box. Does anyone know how to do this?
This is the basic setup that I use for every screen:
package screens
{
import flash.filters.*;
import flash.text.*;
import mapSystem.screenSystem.*;
import mapSystem.*;
import screens.*;
import caurina.transitions.Tweener;
public class screen4 extends screenBase
{
public function screen4(pSystem:mapManager)
{
super(pSystem);
numActions = 1;
}
public override function onAction()
{
if (actionStep == 1)
{
map.fID("54");
}
}
public override function onEnter()
{
map.zoomTo("full");
}
}
}
For users to input text, simply create a textfield and set its "type" property to TextFieldType.INPUT. When you go to retrieve this data, just access the textFields "text" prop.
Update -
Ok = simple google search on "AS3 textField tutorial", first hit was this tutorial, which I yanked and added a couple things to for you. Its fairly basic and well documented, so, depending on your level of experience, should prove illuminating.
//Creating the textfield object and naming it "myTextField"
var myTextField:TextField = new TextField();
//Here we add the new textfield instance to the stage with addchild()
addChild(myTextField);
//Here we define some properties for our text field, starting with giving it some text to contain.
//A width, x and y coordinates.
myTextField.text = "input text here";
myTextField.width = 250;
myTextField.x = 25;
myTextField.y = 25;
//#b99 addition
myTextField.type = TextFieldType.INPUT;
//This is the section for our text styling, first we create a TextFormat instance naming it myFormat
var myFormat:TextFormat = new TextFormat();
//Giving the format a hex decimal color code
myFormat.color = 0xAA0000;
//Adding some bigger text size
myFormat.size = 24;
//Last text style is to make it italic.
myFormat.italic = true;
//Now the most important thing for the textformat, we need to add it to the myTextField with setTextFormat.
myTextField.setTextFormat(myFormat);
Hope that helps!

ActionScript3: Changing button text

I have a button instance named Button that I have in my movie, this instance has a Dynamic Text object in it named myText, how can I change the text? I already tried Button.myText.text = "Stuff";
I get the error "Scene 1, Layer 'Layer 1', Frame 1, Line 7 1119: Access of possibly undefined property myText through a reference with static type flash.display:SimpleButton." When I compile.
AS:
import flash.events.MouseEvent;
TheButton.addEventListener(MouseEvent.CLICK, onClick);
function onClick(Event:MouseEvent):void{
TheButton.myText.text = "Moo";
}
You can't use the dot syntax to access a display object container's child display objects in AS3 as you did in AS2. Normally you would use the display object container's getChildByName() method to get its child display objects, but because your dealing with an instance of SimpleButton which is a subclass of DisplayObject that method doesn't exist. The simple solution is to change you button from a button to a movieclip after which the following should work:
TheButton.addEventListener(MouseEvent.CLICK, onClick);
function onClick(Event:MouseEvent):void
{
TheButton.getChildByName("myText").text = "Moo";
}
Note: the TextField display object in the TheButton display object container must have an instance name of "myText" and obviously the TheButton display object container must have an instance name of "TheButton".
Also if your going with this approach you may want to rewrite the code as follows:
import flash.display.DisplayObjectContainer
import flash.events.MouseEvent;
import flash.text.TextField;
button.addEventListener(MouseEvent.CLICK, onButtonClick);
function onButtonClick(e:MouseEvent):void
{
var button:DisplayObjectContainer = DisplayObjectContainer(e.target);
var textField:TextField = TextField(button.getChildByName("textField"));
textField.text = "Moo";
}// end function
[UPDATE]
Another solution is to create a movieclip/sprite object for the SimpleButton object's upState, overState and downState properties like the following:
import flash.display.DisplayObjectContainer;
import flash.display.SimpleButton;
import flash.display.Graphics;
import flash.display.Shape;
import flash.display.Sprite;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.text.TextField;
var simpleButton:SimpleButton = new SimpleButton();
addChild(simpleButton);
var content:Sprite = new Sprite();
draw(content.graphics, 0xFF0000);
var textField:TextField = new TextField();
textField.name = "textField";
textField.text = "UP";
content.addChild(textField);
simpleButton.upState = content;
simpleButton.overState = content;
simpleButton.downState = content;
simpleButton.hitTestState = content;
simpleButton.addEventListener(MouseEvent.MOUSE_OVER, onSimpleButtonMouseOver);
simpleButton.addEventListener(MouseEvent.MOUSE_DOWN, onSimpleButtonMouseDown);
simpleButton.addEventListener(MouseEvent.MOUSE_OUT, onSimpleButtonMouseOut);
simpleButton.addEventListener(MouseEvent.MOUSE_UP, onSimpleButtonMouseUp);
function onSimpleButtonMouseOver(e:MouseEvent):void
{
var content:DisplayObjectContainer = DisplayObjectContainer(SimpleButton(e.target).overState);
var textField:TextField = TextField(content.getChildByName("textField"));
textField.text = "OVER";
draw(content.graphics, 0xC8C8C8);
}// end function
function onSimpleButtonMouseDown(e:MouseEvent):void
{
var content:DisplayObjectContainer = DisplayObjectContainer(SimpleButton(e.target).downState);
var textField:TextField = TextField(content.getChildByName("textField"));
textField.text = "DOWN";
draw(content.graphics, 0x646464);
}// end function
function onSimpleButtonMouseUp(e:MouseEvent):void
{
var content:DisplayObjectContainer = DisplayObjectContainer(SimpleButton(e.target).overState);
var textField:TextField = TextField(content.getChildByName("textField"));
textField.text = "OVER";
draw(content.graphics, 0xC8C8C8);
}// end function
function onSimpleButtonMouseOut(e:MouseEvent):void
{
var content:DisplayObjectContainer = DisplayObjectContainer(SimpleButton(e.target).upState);
var textField:TextField = TextField(content.getChildByName("textField"));
textField.text = "UP";
draw(content.graphics, 0xFF0000);
}// end function
function draw(graphics:Graphics, color:uint):void
{
graphics.clear();
graphics.beginFill(color)
graphics.drawRect(0, 0, 100, 100);
graphics.endFill();
}// end function
It's extremely easy.
Suppose I have a button that was created from the Components menu called myBtn.
myBtn.label = "Awesome text";
You use label instead of creating a textfield over it then setting the texfield's text.
That's it!
In the absence of extra information as to whether you're getting errors and what they are, my first assumption would be that the system is having trouble with the variable name "Button". There is already a class named "Button", so I would think the system is thinking you are trying to call a class-level method/var of class Button instead of accessing a variable named "Button". I would try changing the name of the button var to something unique.
Children of SimpleButton are inaccessible from Actionscript; notice that it does not actually extend DisplayObjectContainer. The SimpleButton class is a bit of a mutant.
You will have to use a container MovieClip and put the SimpleButton and the label TextField inside. Alternatively you can roll your own button out of a MovieClip or use a component library. SimpleButton is not meant for this kind of use.

AS3 Rounded Text Field

Does anyone know how to create a dynamic textfield with a visible border and rounded corners in AS3?
I think I might have to create a rounded movieclip, resize and place it behind the text.
I tried this, but I don't see any changes.
var styleRound:StyleSheet = new StyleSheet();
styleRound.parseCSS("h4{cornerRadius:10;borderStyle: solid; borderThickness: 1;}");
tf.htmlText = "<h4>" + hotspotData.caption + "</h4>";
tf.styleSheet = styleRound;
Here is a list of the available CSS styles for TextFields in ActionScript 3. Sorry, there is no corner radius.
You can turn on a border for a textfield on the TextField objects border property. But there is not a property available to round the corner.
I suggest you create a new component and add the border yourself as a Sprite underneath the TextField. Something like:
package
{
import flash.display.Graphics;
import flash.display.Sprite;
import flash.text.TextField;
import flash.text.TextFieldAutoSize;
public class TextBorder extends Sprite
{
private static const CORNER_RADIUS:int = 5;
// display objects
private var background:Sprite;
private var field:TextField;
// properties
private var _text:String;
public function TextBorder()
{
background = new Sprite;
field = new TextField;
field.autoSize = TextFieldAutoSize.LEFT;
addChild(background);
addChild(field);
// TESTING:
text = "Hello World";
}
public function set text(newText:String):void
{
_text = newText;
display();
}
public function get text():String
{
return _text;
}
private function display():void
{
field.text = _text;
var g:Graphics = background.graphics;
g.clear();
g.lineStyle(0, 0x0);
g.beginFill(0xFFFFFF);
g.drawRoundRect(0, 0, field.width, field.height, CORNER_RADIUS);
}
}
}
I ended up creating a rounded rectangle in flash and exporting it as its own class - hotspotBG.
var hotspotBackground:hotspotBG = new hotspotBG();
hotspotBackground.width = textField.width + 10;
caption.addChild(hotspotBackground);
You cannot change the text field it self, as of 2014 flash does not allow that.
What you can do is delete the background and the borders,
which will leave the text field completely transparent,
then add an image (rectangle tool is the easiest way to do this) at back of the text field,
so that the text field is on top of the image (z-axis-wise)
It may not be the way you thought of but hell it works!
//you are deleting the background and the borders
//and replacing them with an image
textbox.background=false;
textbox.border=false;
Can you just use the CSS styles? Something like:
TextInput {
borderStyle: solid;
borderThickness: 1;
cornerRadius: 2;
}
I haven't tested this, but that should give you a rounded corner.