Archive for the 'actionscript' Category

26MayEmbeding fonts in flash to display bold the right way

In order to use the <b> tag within html text in flash and have Flash automatically detect the right font to use for bold, you must embed both character sets and specify the fontWeight of both.

Sounds more complicated than it is. Just use the following code when embedding fonts:

[Embed(mimeType='application/x-font', source='fonts/myFont-Medium.ttf', fontName='myfont')]
private var font:Class;

[Embed(mimeType='application/x-font', source='fonts/myFont-Bold.ttf', fontName='myfont', fontWeight='bold')]
private var fontBold:Class;

14MayHTML tags and CSS properties available in Flash 9

  • HTML tags supported
  • Tag Description
    Anchor tag The <a> tag creates a hypertext link and supports the following attributes:

    • target: Specifies the name of the target window where you load the page. Options include _self, _blank, _parent, and _top. The _self option specifies the current frame in the current window, _blank specifies a new window, _parent specifies the parent of the current frame, and _top specifies the top-level frame in the current window.
    • href: Specifies a URL or an ActionScript link event.The URL can be either absolute or relative to the location of the SWF file that is loading the page. An example of an absolute reference to a URL is http://www.adobe.com; an example of a relative reference is /index.html. Absolute URLs must be prefixed with http://; otherwise, Flash treats them as relative URLs. You can use the link event to cause the link to execute an ActionScript function in a SWF file instead of opening a URL. To specify a link event, use the event scheme instead of the http scheme in your href attribute. An example is href="event:myText" instead of href="http://myURL"; when the user clicks a hypertext link that contains the event scheme, the text field dispatches a link TextEvent with its text property set to "myText". You can then create an ActionScript function that executes whenever the link TextEvent is dispatched. You can also define a:link, a:hover, and a:active styles for anchor tags by using style sheets.
    Bold tag The <b> tag renders text as bold. A bold typeface must be available for the font used.
    Break tag The <br> tag creates a line break in the text field. You must set the text field to be a multiline text field to use this tag.
    Font tag The <font> tag specifies a font or list of fonts to display the text.The font tag supports the following attributes:

    • color: Only hexadecimal color (#FFFFFF) values are supported.
    • face: Specifies the name of the font to use. As shown in the following example, you can specify a list of comma-delimited font names, in which case Flash Player selects the first available font. If the specified font is not installed on the user's computer system or isn't embedded in the SWF file, Flash Player selects a substitute font.
    • size: Specifies the size of the font. You can use absolute pixel sizes, such as 16 or 18, or relative point sizes, such as +2 or -4.
    Image tag The <img> tag lets you embed external image files (JPEG, GIF, PNG), SWF files, and movie clips inside text fields. Text automatically flows around images you embed in text fields. To use this tag, you must set the text field to be multiline and to wrap text.The <img> tag supports the following attributes:

    • src: Specifies the URL to an image or SWF file, or the linkage identifier for a movie clip symbol in the library. This attribute is required; all other attributes are optional. External files (JPEG, GIF, PNG, and SWF files) do not show until they are downloaded completely.
    • width: The width of the image, SWF file, or movie clip being inserted, in pixels.
    • height: The height of the image, SWF file, or movie clip being inserted, in pixels.
    • align: Specifies the horizontal alignment of the embedded image within the text field. Valid values are left and right. The default value is left.
    • hspace: Specifies the amount of horizontal space that surrounds the image where no text appears. The default value is 8.
    • vspace: Specifies the amount of vertical space that surrounds the image where no text appears. The default value is 8.
    • id: Specifies the name for the movie clip instance (created by Flash Player) that contains the embedded image file, SWF file, or movie clip. This is useful if you want to control the embedded content with ActionScript.
    • checkPolicyFile: Specifies that Flash Player will check for a cross-domain policy file on the server associated with the image's domain. If a cross-domain policy file exists, SWF files in the domains listed in the file can access the data of the loaded image, for instance by calling the BitmapData.draw() method with this image as the source parameter. For more information, see the "Flash Player Security" chapter in Programming ActionScript 3.0.

    Flash displays media embedded in a text field at full size. To specify the dimensions of the media you are embedding, use the <img> tag's height and width attributes.

    In general, an image embedded in a text field appears on the line following the <img> tag. However, when the <img> tag is the first character in the text field, the image appears on the first line of the text field.

    Italic tag The <i> tag displays the tagged text in italics. An italic typeface must be available for the font used.
    List item tag The <li> tag places a bullet in front of the text that it encloses. Note: Because Flash Player does not recognize ordered and unordered list tags (<ol> and <ul>, they do not modify how your list is rendered. All lists are unordered and all list items use bullets.
    Paragraph tag The <p> tag creates a new paragraph. You must set the text field to be a multiline text field to use this tag. The <p> tag supports the following attributes:

    • align: Specifies alignment of text within the paragraph; valid values are left, right, justify, and center.
    • class: Specifies a CSS style class defined by a flash.text.StyleSheet object.
    Span tag The <span> tag is available only for use with CSS text styles. It supports the following attribute:

    • class: Specifies a CSS style class defined by a flash.text.StyleSheet object.
    Text format tag The <textformat> tag lets you use a subset of paragraph formatting properties of the TextFormat class within text fields, including line leading, indentation, margins, and tab stops. You can combine <textformat> tags with the built-in HTML tags.The <textformat> tag has the following attributes:

    • blockindent: Specifies the block indentation in points; corresponds to TextFormat.blockIndent.
    • indent: Specifies the indentation from the left margin to the first character in the paragraph; corresponds to TextFormat.indent. Both positive and negative numbers are acceptable.
    • leading: Specifies the amount of leading (vertical space) between lines; corresponds to TextFormat.leading. Both positive and negative numbers are acceptable.
    • leftmargin: Specifies the left margin of the paragraph, in points; corresponds to TextFormat.leftMargin.
    • rightmargin: Specifies the right margin of the paragraph, in points; corresponds to TextFormat.rightMargin.
    • tabstops: Specifies custom tab stops as an array of non-negative integers; corresponds to TextFormat.tabStops.
    Underline tag The <u> tag underlines the tagged text.
  • CSS properties
  • These are all the CSS properties that can be manipulated from an external style sheet and with actionscript.

    CSS property ActionScript property Usage and supported values
    color color Only hexadecimal color values are supported. Named colors (such as blue) are not supported. Colors are written in the following format: #FF0000.
    display display Supported values are inline, block, and none.
    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: mono is converted to _typewriter, sans-serif is converted to _sans, and serif is converted to _serif.
    font-size fontSize Only the numeric part of the value is used. Units (px, pt) are not parsed; pixels and points are equivalent.
    font-style fontStyle Recognized values are normal and italic.
    font-weight fontWeight Recognized values are normal and bold.
    kerning kerning Recognized values are true and false. Kerning is supported for embedded fonts only. Certain fonts, such as Courier New, do not support kerning. The kerning property is only supported in SWF files created in Windows, not in SWF files created on the Macintosh. However, these SWF files can be played in non-Windows versions of Flash Player and the kerning still applies.
    leading leading The amount of space that is uniformly distributed between lines. The value specifies the number of pixels that are added after each line. A negative value condenses the space between lines. Only the numeric part of the value is used. Units (px, pt) are not parsed; pixels and points are equivalent.
    letter-spacing letterSpacing The amount of space that is uniformly distributed between characters. The value specifies the number of pixels that are added after each character. A negative value condenses the space between characters. Only the numeric part of the value is used. Units (px, pt) are not parsed; pixels and points are equivalent.
    margin-left marginLeft Only the numeric part of the value is used. Units (px, pt) are not parsed; pixels and points are equivalent.
    margin-right marginRight Only the numeric part of the value is used. Units (px, pt) are not parsed; pixels and points are equivalent.
    text-align textAlign Recognized values are left, center, right, and justify.
    text-decoration textDecoration Recognized values are none and underline.
    text-indent textIndent Only the numeric part of the value is used. Units (px, pt) are not parsed; pixels and points are equivalent.
This content is straight out of the documentation in the Flash help files, but it's always a pain to find.

03MaySWFAddress 2.1 supports Google Analytics

And it does it out of the box.

SWFAddress 2.1 is out and it supports Google Analytics with no extra effort. No code necessary except for the usual SCRIPT tags code provided by Google.

If you are like me and don't like to read all the fine print, keep in mind that you'll have to remove the following code

pageTracker._trackPageview();

from the HTML, because SWFAddress tracks the page view automatically for you. If you don't remove you'll end up with double page visits.

Pages are ready to be tracked. So now to track events:

public static function track(event:String):void
{
    ExternalInterface.call("pageTracker._trackPageview('"+event+"')");
}

And you are all set.

30AprAvoid crossdomain.xml restrictions

Let's go with a little bit of hacking for the masses. Adobe implementation of security relies in some cases on the crossdomain.xml file hosted at the server that holds the data. You can access that data, generally, with your browser, but you can't with the Flash Player if the crossdomain file doesn't allow you. Actionscript will throw a Sandbox violation error.

In many cases we want access to data that is available to us by other means but restricted to Flash by this file. In my case I was trying to access Google Geolocation API from actionscript:
http://maps.google.com/maps/geo?q=...
This is the content of http://maps.google.com/crossdomain.xml :

<cross-domain-policy>
<site-control permitted-cross-domain-policies="by-content-type"/>
</cross-domain-policy>

I have yet to figure out if there is a workaround in actionscript, but I come across a nifty php that will let you overpass those crossdomain restrictions. Here it goes:

crossdomain-proxy.php

<?php
$post_data = $HTTP_RAW_POST_DATA;
$header[] = "Content-type: text/xml";
$header[] = "Content-length: ".strlen($post_data);
preg_match("/url=(.*)/",$_SERVER['REQUEST_URI'],$params);
$ch = curl_init( $params[1] );
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
if ( strlen($post_data)>0 ){
    curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
}
$response = curl_exec($ch);     
if (curl_errno($ch)) {
    print curl_error($ch);
} else {
    curl_close($ch);
    header("Content-type: text/xml; Content-length: ".strlen($response));
    print $response;
}
?>

This code was extracted from Yoppa blog where he goes into detail explaining how to use it. In case your Japanese is rusty here's how it goes.
Instead of requesting the url:

var url:String = "http://maps.google.com/maps/geo?q=...";

we are going to request:

var url:String = "crossdomain-proxy.php?url=http://maps.google.com/maps/geo?q=...";

This bypasses the security error and retrieves the exact same content as the original url.

Now I have to admit that I don't understand every bit of code in that php file, but I checked it first to make sure that my server wasn't going to explode with it, and it works really well..

Php n00bies, beware.

If I were you, I would restrict the calls to this php to my own domain only.

Just to make sure that those smart-ass hackers out there won't use my php's url to retrieve their content.

17AprActionScript Security: About Flash Pirates and Swf Hackers

The very basis of Flash security that concern many content creators is the protection of the intellectual property around websites and other flash powered RIAs. The most common security breach is the easiness to "steal material" from the web (note the quotes).

If it's digital it can't be "stolen"
and it for sure can't be called "material".
  • Flash Pirates
  • Ok, so this is your common guy. Stealing for them can be as easy as checking their browser cache, or fiddling with FireBug and download SWF files or other assets that might be dynamically loaded from the flash (swf files, images, xmls, mp3s, ....). We all know them, and -let's be honest- we all have been there.

    We all have a hacker inside.
    It's the size what makes the difference

    Then again, nosing around your computer cache can hardly be called "stealing", and in many circumstances keeping a file at one's computer for personal use doesn't harm its author either.
    On the other hand one example comes to my mind: Flash Game developers. I have read through the years how some of this developers have seen their games stolen reposted on other sites, and appropriated by others. Something one doesn't want to deal with specially when the intent for the piece of work was freeware software and the copies are being monetized. In this case we are dealing with more than "stealing" we are dealing with "appropriation".

    Flash pirates are numerous, but they lack in many cases further technological knowledge. They can steal but they can't modify. That is the labor of other guys...

  • SWF Hackers
  • These are the clever guys. They will bypass any trick you've set up, and successfully download your SWFs. Then, if they so desire, they will expose your creations inner core. There are out there a handful of decompilers that will do the trick and they keep up to date with their counterpart the obfuscators.

    Sometimes it is a very useful tool for content creators. I'll explain. I recently found about a set of components that an individual was selling on his web when I opened a SWF file in FlashDevelop. I would have never been exposed to this creations if it wasn't for the fact that I check the classes involved on the application. This particular SWF file was nothing but a clever use of Google APIs, PaperVision and some commercial components from this site. If you have released a component or other code, you know that once an author encapsulates their flash there is no easy way to claim that some of your code might be there.

    You can rest assured that, for the hackers, you will always get some credit.
  • So what can you do?
  • OpenSource is a great idea, and probably unavoidable, but for content creators, programmers and artist (they are all the same) this might be a hard road.

    Ask yourself first: Do I have to do something?

    Flash Pirates can be more or less deceived. Protect your work to a minimum and you will be saving yourself from 95% of your work appropriation. Still worried about the rest 5%? It's futile. SWF Hackers can be as persistent and methodological as your browser is. If your content is open to be read and interpreted by a browser, it can be too be read and interpreted by a human given enough time.

    If they want it bad enough
    they will have it.

    "Bad enough" is the key here, and I will be posting some tools and techniques to test how far those hackers are eager to go to open your code. But in the end, remember, you learned from other's code. Be generous and let other learn from you. Spend your time coding the next thing, not protecting what you've already finish!.

    Amen

11AprEasingAround equations: simple easing back and forth

That should be "forth and back".

EasingAround is a class to simplify even more very basic tweens. The idea behind this class is to provide a means to create a tween that starts and ends at the same value.

Download
EasingAround.zip v.1.0.2

If your regular Easing function [from 1 to 10] behaves as follows:

   1 . . . . 5 . . . . 10

then, an EasingAround function with the same parameters behaves as:

   1 . .5. . 10 . .5. . 1

in the same amount of time.

These equations come in handy when we want to create some quick animation -like button rollovers- with the shortest code, without having to "chain" two consecutive tweens.

Example (rollover the icon or click the stage to tween):

This movie requires Flash Player 9

This is the code for the rollover tween:

new Tween(box, "scaleX", EasingAround.easeInOutSine, 1, 2, 0.3, true)
new Tween(box, "scaleY", EasingAround.easeInOutSine, 1, 2, 0.3, true)

This class contains only the easing equations and should be compatible with any AS3 tween engine out there (e.g. Tweener) or with code that uses fl.motion.easing.* or fl.transitions.easing.*

The functions are named as follows:

EasingAround.easeNone

EasingAround.easeInQuad
EasingAround.easeOutQuad
EasingAround.easeInOutQuad
EasingAround.easeOutInQuad

EasingAround.easeInCubic
EasingAround.easeOutCubic
EasingAround.easeInOutCubic
EasingAround.easeOutInCubic

etc...

Note: EasingAround uses the original easing equations by Robert Penner.

07OctAIF Toolkit

For those of you that have done some pixel shading programming, Adobe is bringing into Flash a very interesting project:

Adobe Image Foundation (AIF) Toolkit preview , codenamed Hydra.

Now, if only my card was supported...

06OctAIR: Registering file types

With the last release of AIR beta 2 comes more detailed file type asociation.

This is the fileTypes tag in the AIR configuration XML:

<fileTypes>
      <fileType>
          <name>com.example</name>
          <extension>xmpl</extension>
          <description>Example file</description>
          <contentType>example/x-data-type</contentType>
            <icon>
              <image16x16>icons/AIRApp_16.png</image16x16>     
              <image32x32>icons/AIRApp_32.png</image32x32>     
              <image48x48>icons/AIRApp_48.png</image48x48>     
              <image128x128>icons/AIRApp_128.png</image128x128>
            </icon>
      </fileType>
</fileTypes>

There's a description of some of these paremeters at the Adobe Live Docs site.

The code above, registers the types with your application, so the AIR app is open upon clicking any file with the right extension. In order to perform an action (eg. open), we need to retrieve the value of such file.

To do so we need to add the following code to the "invoke" event in the WindowedApplicaton ( invoke="onInvoke(event) ):

public function onInvoke(invokeEvent:InvokeEvent):void
{
   //trace("Invoke event received.");
                    
   if(invokeEvent.arguments.length> 0){
      trace("Application opened with: "+event.arguments[0]); // file path
      // ...
      // custom code
      // ...
   } else {
      trace("--no arguments--");
   }
}

Again, at Adobe you can find more details.

Finally, if you want a full detailed tutorial go over to Setting Up an AIR Application with File Associations where you'll find an excellent step-by-step guide by senocular.

06OctCreate AIR applications out of your old AS2 code

If you have some old AS2 code laying around that you'd like to take into the desktop, here you have a quick tip that might save you hours of re-coding those AS2 classes into AS3.

In my case, I had an AS2 project completed that I had long ago converted into an executable with Screenweaver. I needed to change a couple of things, and it was then when I realized that Screenweaver was obsolete and would not run in Vista.

Of course AIR is the "desktop publisher" of choice right now, but AIR supports only AS3. The solution comes (using Flex) with an easy SWFLoader, that simply performs an old loadMovie, effectively loading your AS2 movie into AS3. Create a wrapper AS3 class that simply loads your AS2 movie, and create your application with AIR.

You'll need to create a WindowedApplication class to substitute the default class created by Flex.

AS2AIR.as

package com.domain
{
    import mx.core.WindowedApplication;
    import mx.controls.SWFLoader;
   
    public class AS2AIR extends WindowedApplication
    {
        public var swf:SWFLoader;
       
            public function init():void
            {
                this.swf.source = "My_Old_AS2_Code.swf";
            }
    }
}

And the MXML file contains just that SWFLoader.

AS2AIR.mxml

<xml version="1.0" encoding="utf-8"?>

<app:AS2AIR
    xmlns:mx="http://www.adobe.com/2006/mxml"
    xmlns:app="com.domain.*"
    initialize="init();" width="800" height="600"
    layout="absolute" xmlns:ns1="*">

<mx:SWFLoader id="swf" scaleContent="false" width="100%" height="100%" x="0" y="0"/>
   
</app:AS2AIR>

You can, of course, indicate the source file direclty in the MXML file, but if you need to manage some communication between your AIR application and your AS2 movie, you'll have to deal with your own AS class.