Loading External CSS StyleSheets in Flash9 / AS3 / CS3
June 1, 2007 — drawkExternal CSS stylesheets can be used with flash AS3. This is possible with the StyleSheet class in AS3 and controls such as TextField have a property for the stylesheet.
AS2
var styles:TextField.StyleSheet = new TextField.StyleSheet();
styles.onLoad = function(success:Boolean):Void {
if (success) {
// display style names.
trace(this.getStyleNames());
} else {
trace("Error loading CSS file.");
}
};
styles.load("styles.css");
OR apply to a StyleSheet object that can be used for many controls
AS3
package
{
import flash.display.Sprite;
import flash.events.Event;
import flash.net.URLLoader;
import flash.net.URLRequest;
import flash.text.StyleSheet;
import flash.text.TextField;
import flash.text.TextFieldAutoSize;
public class CSSFormattingExample extends Sprite
{
var loader:URLLoader;
var field:TextField;
var exampleText:String = "<h1>This is a headline</h1>" +
"This is a line of text. <span class="bluetext">" +
"This line of text is colored blue.</span>";
public function CSSFormattingExample():void
{
field = new TextField();
field.width = 300;
field.autoSize = TextFieldAutoSize.LEFT;
field.wordWrap = true;
addChild(field);
var req:URLRequest = new URLRequest("example.css");
loader = new URLLoader();
loader.addEventListener(Event.COMPLETE, onCSSFileLoaded);
loader.load(req);
}
public function onCSSFileLoaded(event:Event):void
{
var sheet:StyleSheet = new StyleSheet();
sheet.parseCSS(loader.data);
field.styleSheet = sheet;
field.htmlText = exampleText;
}
}
}
[SOURCE]
Flash is limited in CSS support and only supports CSS1 properties and a minimal amount for formatting.
Supported CSS properties
Flash Player supports a subset of properties in the original CSS1 specification (www.w3.org/TR/REC-CSS1). The following table shows the supported CSS properties and values as well as their corresponding ActionScript property names. (Each ActionScript property name is derived from the corresponding CSS property name; the hyphen is omitted and the subsequent character is capitalized.)
CSS property ActionScript property Usage and supported values text-align textAlign Recognized values are left,center, right, andjustify.text-decoration textDecoration Recognized values are noneandunderline.margin-right marginRight Only the numeric part of the value is used. Units (px, pt) are not parsed; pixels and points are equivalent. kerning kerning Recognized values are trueandfalse.letter-spacing letterSpacing Only the numeric part of the value is used. Units (px, pt) are not parsed; pixels and points are equivalent. font-family fontFamily A comma-separated list of fonts to use, in descending order of desirability. Any font family name can be used. If you specify a generic font name, it is converted to an appropriate device font. The following font conversions are available: monois converted to_typewriter,sans-serifis converted to_sans, andserifis converted to_serif.display display Supported values are inline,block, andnone.For an example of using styles on XML elements, see An example of using styles with XML.
June 4, 2007 at 4:58 am
nice blog.
looking forward to read more!
and sorry, but actionscript 3.0 is really hard to understand, I think.
so here’s my rookiequestion.
I’ve added this code to my file:
var styles:TextField.StyleSheet = new TextField.StyleSheet();
styles.onLoad = function(success:Boolean):Void {
if (success) {
// display style names.
trace(”this is the styles name: “+this.getStyleNames());
} else {
trace(”Error loading CSS file.”);
}
};
styles.load(”styles.css”);
/*
content of styles.css:
//
body {
background-color: #cccccc;
width: 400px;
height: 300 px;
border: 1px solid #4b4b4b;
margin: 10px auto;
text-align: center;
}
//
h1 {
margin: 0;
font-family: verdana, arial, sans-serif;
color: #4c4c4c;
font-size: 14px;
font-weight: bold;
}
//
h2 {
color: #999999;
font-family: verdana, arial, sans-serif;
font-size: 12px;
font-weight: bold;
}
//
p {
font-family: verdana, arial, sans-serif;
color: #000000;
font-size: 11px;
}
//
p.Right {
text-align: right;
}
//
#content {
text-align: left;
background-color: #ffffff;
padding: 10px;
}
*/
how do I actionscript a textfield, that uses this .css-file?
thanks in advance
felisan
June 4, 2007 at 10:54 am
Hey felisan. You are on the right track all you have to do now is set htmlText of your textbox to include spans or classes from your stylesheet. i.e.
var label:TextField = new TextField();
label.styleSheet = style;
label.htmlText = “Hello World…”;
June 25, 2007 at 2:51 pm
I’m receving an error when i compile the file …
1046: Type was not found or was not a compile-time constant: Void.
What can i do ?
June 26, 2007 at 7:24 am
RaQ: Void needs to be lowercased in AS3… Use “void” instead.
October 11, 2007 at 3:28 pm
How does this work with TextArea? I tried using setStyle(”textFormat”, myFomat) but I’m not getting anything.
October 11, 2007 at 8:22 pm
Hey Jason,
Are you immediately setting it or doing it in the onload of the css file in flash? If you set it without waiting for it to load it will not whos.
Also, setStyle is an older AS1 method. The above samples are as2 and for AS3 especially where you have StyleSheet classes that you set to the .styleSheet properties.
Then you just use html tags like to set styles to in the TextAreas.
# public function onCSSFileLoaded(event:Event):void
# {
# var sheet:StyleSheet = new StyleSheet();
# sheet.parseCSS(loader.data);
# field.styleSheet = sheet;
# field.htmlText = exampleText;
# }
October 23, 2007 at 3:35 pm
I’m looking at the as3 example starting on line 16. Will this cause an “Error 1095: The string literal must be terminated before the line break.”?
Also, do you need to escape the quotes around “bluetext” in line 21 or does as3 somehow figure that all out?
February 20, 2008 at 11:30 am
i see to be having an issue using this code to format external text loads. is there an alternative code i need when trying to format external text? thanks.
var external_txt:TextField = new TextField();
var externalReq:URLRequest = new URLRequest(”aboutus.txt”);
var externalLoad: URLLoader = new URLLoader();
externalLoad.load(externalReq);
externalLoad.addEventListener(Event.COMPLETE, textReady);
{
external_txt.text = event.target.data;
}
external_txt.x = 104;
external_txt.y = 140;
external_txt.width = 522;
external_txt.height = 272;
addChild(external_txt);
var styles:TextField.styleSheet= new TextField.styleSheet();
styles.onLoad = function(success:Boolean):void {
if (success) {
trace(this.getStyleNames());
} else {
trace(”Error loading CSS file.”);
}
};
styles.load(”styles.css”);
February 20, 2008 at 8:00 pm
Hey Thomas,
You need to set the text property of htmlText and then also when you have the styles object set it to the styles formatter.
field.styleSheet = sheet;
field.htmlText = exampleText;
Or for your specific samples
external_txt.styleSheet = styles;
external_txt.htmlText = event.target.data;
March 7, 2008 at 8:29 am
I would like to know how to write to a file in actionscript.could someone illustrate that to me
March 11, 2008 at 9:29 am
Hi, i’ve tried this example (exactly like it is) and it gives me no errors but the textfield doesn’t get formated! Anyone has any idea why this could hapen??
thanks
March 13, 2008 at 9:21 am
ok so i have this code(below) and i want to style the text, as in change the font, textcolor, size, etc. I dont know what i am doing and i am sooo frustrated, please help. cs3 as3
var eMain_txt:TextField = new TextField();
var eMainReq:URLRequest = new URLRequest(”text/eMain.txt”);
var eMainLoad:URLLoader = new URLLoader();
var eCap_txt:TextField = new TextField();
var eCapReq:URLRequest = new URLRequest(”text/eCap.txt”);
var eCapLoad:URLLoader = new URLLoader();
eCapLoad.load(eCapReq);
eMainLoad.load(eMainReq);
eMainLoad.addEventListener(Event.COMPLETE, eMainReady);
eCapLoad.addEventListener(Event.COMPLETE, eCapReady);
up_btn.addEventListener(MouseEvent.CLICK, scrollUp);
down_btn.addEventListener(MouseEvent.CLICK, scrollDown);
eMain_txt.x = 245;
eMain_txt.y = 80;
eMain_txt.border = false;
eMain_txt.width = 174.9;
eMain_txt.height = 620;
eMain_txt.wordWrap = true;
eCap_txt.x = 36;
eCap_txt.y = 223.3;
eCap_txt.border = false;
eCap_txt.width = 186;
eCap_txt.height = 109;
eCap_txt.wordWrap = true;
addChild(eCap_txt);
addChild(eMain_txt);
function eMainReady(event:Event):void
{
eMain_txt.htmlText = event.target.data;
}
function eCapReady(event:Event):void
{
eCap_txt.text = event.target.data;
}
function scrollUp(event:MouseEvent):void
{
eMain_txt.scrollV –;
}
function scrollDown(event:MouseEvent):void
{
eMain_txt.scrollV ++;
}
March 13, 2008 at 12:29 pm
robert you are almost there. You just need to now have a Stylesheet object that you can load from a css file or use flash to create (flash internally uses names without the “-” in them.
Where loader.data is from the css file.
var req:URLRequest = new URLRequest(”example.css”);
loader = new URLLoader();
loader.addEventListener(Event.COMPLETE, onCSSFileLoaded); loader.load(req);
public function onCSSFileLoaded(event:Event):void
{
var sheet:StyleSheet = new StyleSheet();
sheet.parseCSS(loader.data);
field.styleSheet = sheet;
field.htmlText = exampleText;
}
Be sure your htmlText data has the HTML tags in it like etc. Also one thing about flash HTML is it only supports limited tags. See above for all the styles it supports.
You can also look at wrapper or flashml to look at HTML to flash conversion which can handle more like divs and tables etc.
March 25, 2008 at 6:58 am
ok so what i want to be able to do is load some xml data into flash, then be able to change it around in flash and then save the data over the original xml file.. (pretty much just a simple flash cms, using an xml file instead of a database)
now i know actionscript very well, however thats about it.. don’t really know any other languages, like php, asp, etc etc..
im guessing the easiest way to do this is to import the xml data, change it, place it within a variable, and then have some kind of script overwrite the oringal xml file with the variable.
anyone able to help me out?
March 25, 2008 at 3:46 pm
Hey Humble,
Here there are lots of ways. You will need external server script to help you save it to the file system (flash can’t do that by itself due to security).
You could:
- simple post it to a php or asp.net file that would then save the post variable to the file
- use a service (web service or json service) to catch the remoting call and save it to disk
- use a service to do a partial update (so you can stream the file and not kill the entire app when the file is writing)
You can accomplish the first items with a URL loader with params.
The second way you will need to have some service knowledge to pull off with NetConnection, PendingResult etc.
March 26, 2008 at 8:31 am
I appreciate the information but is it possible that you could further clarify the consept of server script or show me an example?Because the software i have to create is a selfcontain application which is suppost to be installed in the user’s machine, played and store results and user name with any internet connection.
I am sorry for any incovinience is just that i’ve made so many attempts and now i am running out of time.
please if methods u describe abouve doesn’t require interenet connection in order to work then please illustrate it to me
March 26, 2008 at 8:31 am
thank you in advance
March 26, 2008 at 2:31 pm
HumbleOne. The only way flash can save locally is by using an SWF2EXE like MDM zinc or Adobe AIR. Flash by itself cannot write to the file system for security reasons. But AIR sounds like a perfect candidate for you. It is meant for desktop flash and has access to system info and files.
March 26, 2008 at 3:09 pm
thanxs i’ll have a look at that
April 17, 2008 at 2:17 am
Dont suppose you know anything about implementing Line-height? Its supported within the TextFormat class (leading) so its possible within AS3 but the CSS property (line-height) is not supported when using an external style sheet.
Ive found a few hacks around for AS2 but nothing on AS3 and wouldnt know where to start on migrating them.
Any insight Id love to know,
great site btw
g
April 17, 2008 at 11:58 am
Hey George,
I don’t think flash supports the line-height as it is not in the supported CSS list above. If is is there it will be lineHeight. Although not all hope is lost there are some great kits like flash wrapper and FlashML that convert HTML to flash and they have methods in there to get around some css that is not supported in flash (since flash css and html support is pretty ancient).
June 2, 2008 at 9:37 pm
Hey guys, for line-height, try leading. (default is 2)
leading:0;
June 16, 2008 at 8:48 am
I’ve noticed an issue when using class in the CSS and then trying to style the hover, link and rollover effects of that class. Flash seems to hate that and none of the text is styled in the text field.
.className
{
}
.className a:hover
{
}
.className a:link
{
}
.className a:visited
{
}
when importing into Flash it just ignores the entire style.
I’ve also been using this nice little class that I wrote to handle my CSS loading:
package com.barkley
{
import flash.text.*
import flash.events.*
import flash.net.*
public class cssStyle
{
public var urlLoader:URLLoader
private var css:StyleSheet
private var callback:Function
public function cssStyle(path:String, _callback:Function)
{
callback = _callback
urlLoader = new URLLoader()
urlLoader.addEventListener(Event.COMPLETE, cHandler)
urlLoader.load(new URLRequest(path))
}
private function cHandler(e:Event):void
{
css = new StyleSheet()
css.parseCSS(urlLoader.data)
callback()
}
public function getCSS():StyleSheet
{
return this.css
}
}
}
All works fine as long as I’m not using custom link styles in the CSS Class.
June 18, 2008 at 3:07 pm
Working on menu buttons that control the External Text with AS3. I have everything working with the main menu button, but when trying to get buttons with in a page to control the External Text i get an error and the site wont run.
code for my a button that work in the main stage.
home_btn.addEventListener(MouseEvent.CLICK,b1Listener);
function b1Listener(event:MouseEvent):void {
loadFile(”external.txt”);
sections.gotoAndStop(”home”);
}
Ok but now say you are on the artist page and want to display infomation on each artist once that artist is clicked. the button is not on the main stage its main stage then sections. this is the code i tried.
sections.skinner_btn.addEventListener(MouseEvent.CLICK,b8Listener);
function b8Listener(event:MouseEvent):void {
loadFile(”skinnerl.txt”);
sections.gotoAndStop(”skinner”);
}
Whats wrong?
July 8, 2008 at 10:11 am
solution for using textArea.textField with css bug see http://www.sharedknowhow.com/2008/07/fixed-flash-textarea-css-incompatibility/
July 15, 2008 at 2:59 pm
To yav:
the order is wrong:
a:link {}
a:visited {}
a:hover {}
‘hover’ should always be defined last …
stupid … I know … but it should work