• Home
  • contact
  • Flex:Tips
    • Populate a Datagrid from an ArrayCollection
  • Flash:Tips
  • About Me
  • Posts
  • Comments
  • Email

Brian Connatser – RIA Developer

  • Home
  • Enterprise Development
  • Frameworks
  • Geek stuff
  • Training
  • Web and RIA
    • ActionScript
    • Flex

AS3: Adding motion blur to a Tween in Flash CS3

Posted on 01. Jan, 2010 by Brian Connatser.

5

Updated: For even more info on motion blurring with AS3, check out this post.

The other day I needed to help out a co-worker and create some menu animation in Flash CS3. To set the stage, there are 4 bars that come out from left to right, each in a slightly different default position and each needed independent characteristics. After setting up the initial project, creating the buttons, etc. I began the AS3 code needed to move the bars. To simplify the article I am just using one bar. In my project I am calling a method containing conditionals (if/then) to determine whether the button stays or not. My full code example will be given later.

To move a instance of a movieclip in AS3 you will need to call the following classes:

import fl.transitions.*;
import fl.transitions.Tween;
import fl.transitions.easing.*;

Then create a listener to call the method, which is a bit of code created give a button access to method. A listener defines the event for which to call the method (function) that contains the code we want to run. In this case I am using a MouseEvent event with a value of MOUSE_OVER, which is case sensitive. mainBtn01 corresponds to the instance name of the button, btnBaropen corresponds to the method name that we are calling.

mainBtn01.addEventListener(MouseEvent.MOUSE_OVER, btnBaropen);

To start moving the button we will need to set a Tween variable:

var btnTween:Tween;

Now we can create the method containing the Tween parameters. btnTween relates to the new var we set for a new Tween, the we create a new Tween and follow with the values. btnBar01 relates to the button instance name, “x” relates to the x coordinate, Strong.easeOut relates to the motion – so the button comes out with emphasis and eases out, the first -150 is the starting x coordinate, and 4 is the second x coordinate, .25 relates to 1/4 of a second, and true makes the preceding statement of .25 become a “second”. Without using true the value of time is in milliseconds.

function btnBaropen(event:MouseEvent):void{
     btnTween = new Tween(btnBar01, "x", Strong.easeOut, -150, 3, .25, true);
}

You can also use the new Transition Manager classes. Without getting in to detail, the following is an example of an instance being faded in with the Transition Manager class.

TransitionManager.start(btn01, {type:Fade, direction:Transition.OUT,
duration:.5, easing:None.easeNone, ccw:true});

Now for the coolness, adding motion blur the bar in and out. We only want the bar to look like it is moving sideways, so we will only blur on the x coordinate. To use this function we will need to call a few more classes.

import flash.display.Sprite;
import flash.filters.BitmapFilterQuality;
import flash.filters.BlurFilter;

Then we set our listeners to watch for the beginning of the bar movement, remember it is btnTween, and the finish of the movement. We will use the TweenEvent:MOTION_CHANGE value to watch for the beginning, and TweenEvent:MOTION_FINISH value to watch for the end. One listener will call a method to start the blur (blurOn) and the other to stop the blur (blurOff).

btnTween.addEventListener(TweenEvent.MOTION_CHANGE, blurOn);
btnTween.addEventListener(TweenEvent.MOTION_FINISH, blurOff);

Finally we will create the methods to control the blur effects that our listeners are invoking. Our first method (second is similar so I will only detail the first) is called blurOn and is a TweenEvent. We set a variable “blur” as a BlurFilter and then create a new instance of that BlurFilter. I am only going to blur X, so blur.blurX = 3. I am setting the quality at Medium, and then assigning the bar with the blur filter. So you can see blurOn sets a blur on the X coordinate, then blurOff turns the blur off when the motion is complete. Pretty simple, no?

function blurOn(event:TweenEvent):void{
    var blur:BlurFilter = new BlurFilter();
    blur.blurX = 3;
    blur.blurY = 0;
    blur.quality = BitmapFilterQuality.MEDIUM;
    btnBar01.filters = [blur];
    }

function blurOff(event:TweenEvent):void{
    var blur:BlurFilter = new BlurFilter();
    blur.blurX = 0;
    blur.blurY = 0;
    blur.quality = BitmapFilterQuality.MEDIUM;
    btnBar01.filters = [blur];
    }

So, now here is the completed script:

import fl.transitions.*;
import fl.transitions.Tween;
import fl.transitions.easing.*;
import flash.display.Sprite;
import flash.filters.BitmapFilterQuality;
import flash.filters.BlurFilter;
    //Button listener to call the open and blur funtion
    mainBtn01.addEventListener(MouseEvent.MOUSE_OVER, btnBaropen);

   //Sets tween object, moves bar across screen
    var btnTween:Tween;

    //Method to slide out button bar and half circles, based on Mouse event
    function btnBaropen(event:MouseEvent):void{

       btnTween = new Tween(btnBar01, "x", Strong.easeOut, -150, 20, .25, true);

       //Listener to control Blur on/off
        btnTween.addEventListener(TweenEvent.MOTION_CHANGE, blurOn);
        btnTween.addEventListener(TweenEvent.MOTION_FINISH, blurOff);

        //Method to control blur
        function blurOn(event:TweenEvent):void{
            var blur:BlurFilter = new BlurFilter();
            blur.blurX = 3;
            blur.blurY = 0;
            blur.quality = BitmapFilterQuality.MEDIUM;
            btnBar01.filters = [blur];
            }
        //Method to control blur OFF
        function blurOff(event:TweenEvent):void{
            var blur:BlurFilter = new BlurFilter();
            blur.blurX = 0;
            blur.blurY = 0;
            blur.quality = BitmapFilterQuality.MEDIUM;
            btnBar01.filters = [blur];
            }
}

Related Articles:

  • AS3: More blurring in Flash CS4
  • AS3: Object References and Garbage Collection, by Colin Moock
  • AS3: Accessing Yahoo Finance with Flash, using ColdFusion as a proxy.
  • FDOT – Trying out Ted Patrick’s collection of AS3 classes that make hard things easier.
  • Flex – AS3: Creating Custom Events
  • Continue Reading

    RIABeardoff – For the Kids

    Posted on 01. Dec, 2009 by Brian Connatser.

    2

    Inspired by Elad Elrom, and all the great Flash designers and developers already contributing, I have decided to give some incentive to donate to the RIABeardOff. The RIABeardOff, started by Chuck Freedman, is a very generous charity event  that lets the members of the RIA community grow beards to raise funds for the Marine Toys for Tots Foundation. I myself am somewhat of the unknown in the group of unbelievable contributors, most of which I have looked up to for a number of years and have learned a lot from all of them. Some of the contributors are:

    • Jose Antonio Marquez Russo (@joseeight)
    • Art W
    • Val Head
    • Tom Green
    • Rachel Luxemburg
    • LordAlex Leon
    • Stacey Mulcahy ( BitchWhoCodes)
    • Bernie & Erikka Perkins
    • Mims H. Wright
    • Scott Janousek
    • Chris Allen
    • Curt Staubach (@curtStaubach)
    • Paul Gregoire (@mondain)
    • @BenStucki
    • Todd Anderson (@bustardcelly)
    • Robert Hall (@rhall)
    • Joseph Labrecque (@JosephLabrecque)
    • Jesse Freeman (@theflashbum)
    • Kevin Suttle (@kevinSuttle)
    • Brian Connatser (@connatser) <- me :)
    • Elad Elrom (@EladElrom)
    • Chuck Freedman (@chuckstar)

    So, I will donate not only my “attempt” at growing a beard but 1 (one) full year of web hosting on my Cloud Account at The Rackspace Cloud, from 1-1-10 until 12-31-10. One lucky winner will be chosen at random on the close of the beard off and I will hand the keys to a full year of hosting over to them at that time. The account would consist of 1GB of storage, 2GB of transfer, 15 email accounts, 5 MySQL databases, and I will even throw in the 24 hour awesome support account from The Rackspace Cloud team at my cost. The winner can use this account however they please, as long as it falls within the rules of Rackspace…sorry no porn! All you need to do to enter is donate in my name (@connatser). Karma has been good to me this year and it’s time to give back, please do the same and make a needy child’s holiday one to remember.

    Donate to the RIABeardOff here.

    Continue Reading

    AS3, CF & AIR: Creating a static XML file for use with a StockTicker

    Posted on 23. Nov, 2009 by Brian Connatser.

    0

    stockAIR
    To build off of a couple posts earlier, the following is an example of how to access the Yahoo stock information and create a static XML with AIR file that Flash can access. I went this route after seeing the server hit that we took when 3k+ users logged in at the same time and tried to access the stock ticker. The stock ticker was hitting the Yahoo service every few seconds and was significantly slowing things down. What I decided to do was to still use the CF service to access the stocks, but instead hit it with an AIR app that then takes that information and creates a static XML file for the Flash stock ticker to access. This also solved the “after hours” stock information as the Flash file would always be hitting the static XML, which wouldn’t change after 5:00 PM. So, to define the process, Yahoo delivers stock information, the AIR application is triggered by the server via a scheduled task, AIR accesses the ColdFusion file that hits Yahoo for the stock information, then AIR takes that information and creates a static XML file. This basically took the hit to Yahoo to once every 5 minutes by ONE application, rather than once every few seconds by any number of web hits…typically at least 1k…

    Here is the ColdFusion code to hit Yahoo and gain access to the stock information:

    <cfset urlAddress_Google="http://download.finance.yahoo.com/d/quotes.csv?s=GOOG&f=sl1d1t1c1ohgv&e=.csv" />
    <cfhttp url="#urlAddress_Goog#" method="GET" resolveurl="Yes" throwOnError="Yes"/>
    <cfset stockCompanyName01 = "Google">
    <cfset stockInfo01 = CFHTTP.FileContent>
    
    <cfset urlAddress_Dow="http://download.finance.yahoo.com/d/quotes.csv?s=^DJI&f=sl1d1t1c1ohgv&e=.csv" />
    <cfhttp url="#urlAddress_Dow#" method="GET" resolveurl="Yes" throwOnError="Yes"/>
    <cfset stockCompanyName02 = "Dow">
    <cfset stockInfo02 = CFHTTP.FileContent>
    
    <cfprocessingdirective suppresswhitespace="Yes">
    <cfcontent type="text/xml; charset=utf-16">
    
    <cfxml variable="xmlobject">
    <stocks>
    <company name="<cfoutput>#stockCompanyName01#</cfoutput>" >
    <cfoutput>#stockInfo01#</cfoutput>
    </company>
    <company name="<cfoutput>#stockCompanyName02#</cfoutput>" >
    <cfoutput>#stockInfo02#</cfoutput>
    </company>
    </stocks>
    </cfxml>
    
    <cfset baseStock=toString(xmlobject)>
    <cfset finalStock=replace(baseStock, "UTF-8", "utf-16")>
    
    <cfoutput>#finalStock#</cfoutput>
    
    </cfprocessingdirective>
    

    Here is the AIR code to hit the ColdFusion file:

    <?xml version="1.0" encoding="utf-8"?>
    <mx:WindowedApplication xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" width="300" height="100" creationComplete="init()">
    
    <mx:Script>
    <![CDATA[
    import mx.rpc.events.FaultEvent;
    import mx.rpc.Fault;
    import mx.rpc.events.ResultEvent;
    
    //VARIABLES
    [Bindable]
    private var stockXML:XML;
    
    [Bindable]
    private var sourcePath:String = "[PATH TO CF FILE]";
    
    [Bindable]
    private var stream:FileStream;
    
    [Bindable]
    private var stockSourcePath:String = "[PATH TO SAVE XML]";
    
    //INITIALIZATION METHODS
    private function init():void{
    stockService.send();
    }
    
    private function stockResultHandler(event:ResultEvent):void{
    stockXML = event.result as XML;
    saveFile();
    }
    
    private function stockFaultHandler(event:FaultEvent):void{
    //Fault Handler
    }
    
    ]]>
    </mx:Script>
    
    <mx:Script>
    <![CDATA[
    
    public var stockFile:File = new File();
    
    public function openFile():void{
    stockFile.nativePath = stockSourcePath;
    stream = new FileStream();
    stream.open(stockFile, FileMode.READ);
    var str:String = stream.readUTFBytes(stream.bytesAvailable);
    stream.close();
    saveFile();
    }
    
    public function saveFile():void{
    stockFile.nativePath = stockSourcePath;
    var stream:FileStream = new FileStream()
    stream.open(stockFile, FileMode.WRITE);
    var str:String = stockXML;
    stream.writeUTFBytes(str);
    stream.close();
    
    //Auto closes the AIR App
    this.close();
    }
    
    ]]>
    </mx:Script>
    
     <mx:HTTPService id="stockService" url="{sourcePath}" resultFormat="e4x" result="stockResultHandler(event);" fault="stockFaultHandler(event);"/>
     <mx:Label x="41" y="37" text="GENERATING - KG Stocks" fontSize="15" fontFamily="Verdana" fontWeight="bold" color="#000000"/>
    
    </mx:WindowedApplication>
    

    Related Articles:

  • AS3: Accessing Yahoo Finance with Flash, using ColdFusion as a proxy.
  • AS3: Adding motion blur to a Tween in Flash CS3
  • RIABeardoff – For the Kids
  • AS3: Object References and Garbage Collection, by Colin Moock
  • FDOT – Trying out Ted Patrick’s collection of AS3 classes that make hard things easier.
  • Continue Reading

    Rackspace Cloud – I have a referral program.

    Posted on 13. Nov, 2009 by Brian Connatser.

    0

    rackspaceA few weeks ago I was talking to Jonnie Hallman of DestroyToday.com and DestroyTwitter.com about hosting space. I mentioned that I had a bunch of unused space and would be happy to host his site on my cloud instance. While talking with Jonnie I contacted Rackspace about a referral program, which actually was in works but not yet available. Annnnyway, they have set up a referral program early for me in case anyone is looking to start hosting on the cloud at Rackspace. I would like to think that my awesome blogging skills lead to the early referral program, but for some reason I think it was the connection with Jonnie ;) .

    When creating a cloud account on Rackspace just use REF-Connatser as the code. This will save you $25 off of your first months cost. I know it isn’t a great savings, but every lit bit helps.

    Continue Reading

    RIAUnleashed – Boston

    Posted on 08. Nov, 2009 by Brian Connatser.

    0

    riaunleashed

    I will be at RIAUnleashed this week in Boston. It should be a great time and I am looking forward to meeting as many people as I can. It’s a sold out gig and should be a blast.

    Continue Reading

    New personal site in full effect

    Posted on 08. Nov, 2009 by Brian Connatser.

    0

    brianConnatser

    Ok, it has been years since I have built a personal site, but every now and then I get in that funk… It’s not anything special but it is a full AS3 coded site, no timeline usage, and fully dynamic with XML…so I can update it very easy. I can throw the source code on here if anyone is interested. I am using a lot of custom classes that I wrote, image loaders, pre-loader bars and classes, custom XML aggregators, etc. Also there are a lot of examples of how to use GTween and FDOT, for those wanting to mess around with it. The code is fairly commented, but I will clean it up if someone wants it. Enjoy, or if not keep it to yourself! Nah really, if you hate it or whatever just let me know why. I would be happy for the critique.

    Click here to visit brianconnatser.com

    Continue Reading

    PHP: Access CSV content from Yahoo Stocks with a PHP Proxy.

    Posted on 25. Oct, 2009 by Brian Connatser.

    4

    To follow a recent post about AS3 and Yahoo stocks using ColdFusion as a proxy below is some code to get the same information using PHP. I have been asked by several people on how to do this with PHP, which is not my typical scripting language. I decided to dig into it to see what the comparable method in PHP is to CFHTTP.FileContent. Turns out that the comparable function in PHP is “file_get_contents”.

    <?php
    //Get the file content and assign the string to $teststock
    $teststock = file_get_contents('http://download.finance.yahoo.com/d/quotes.csv?s=^DJI&f=sl1d1t1c1ohgv&e=.csv');
    
    //Split the string into an array to access each property of the stock
    $teststring = split(",",$teststock);
    
    //Print the new array to the screen
    print_r($teststring);
    
    print("<br /><br />");
    
    //Print a specific point in the array, in this case the first one
    print_r($teststring[0]);
    
    print("<br /><br />");
    
    //Print a specific point in the array, in this case the second one
    print_r($teststring[1]);
    
    ?>
    
    
    

    Related Articles:

  • CodeIgniter – Kick ass Open Source PHP Framework.
  • Continue Reading

    AS3: Accessing Yahoo Finance with Flash, using ColdFusion as a proxy.

    Posted on 09. Oct, 2009 by Brian Connatser.

    2

    After searching high and low for a good resource of semi-up-to-the-minute updated stock feeds I came to the conclusion that there aren’t any, for free anyway. I dug into the Google Finance and Data API’s, and made a lot of headway there writing the authentication methods in JavaScript, then in PHP, then in .NET…but was not able to pull something together (quickly) . I plan on revisiting that path, but I digress. I turned to the Yahoo file download that you access via http and it returns a .csv full of stock data from opening trade, current change, volume, etc. This was perfect but how do I convert that to a format that Flash can read?

    I used the URLLoader method to load the data, converted it to an Array by splitting at the commas, and then loaded the different values I need by accessing a certain part of the array. This worked perfectly, locally, but then I placed it on our intranet (final resting place), and nothing showed up. Come to find out, the cross domain policies were preventing access to the file on Yahoo’s server. So to make things easier in the long run I wrote a proxy in ColdFusion that the Flash app calls to obtain the stock data. Enough of my explanations and on to the meat…

    Click here to download the source files.

    I set this project up in FDT and created my normal environment, custom classes, etc. I will include my source files as a zip so you can use it…but will try to explain as best as possible. The files I used are detailed below:

    1. /assets/stockSource.xml
      1. Contains company information and path to the CF Proxy.
    2. com/connatserdev/Stock_Ticker_DC.as
    3. com/connatserdev/events/TickerEvents.as
    4. com/connatserdev/model/Ticker.as
      1. Main class that sets up the XMLSource and YahooStock
    5. com/connatserdev/model/XMLSource.as
      1. Calls the config xml service
    6. com/connatserdev/model/YahooStock.as
      1. Calls the Yahoo service on each loop.

    But…basically to access a FREE non web service based stock ticker source from Yahoo, you would need:

    1. ColdFusion page to deliver the feed results from Yahoo, via CFHTTP.FileContent.
    2. Flash file to access the ColdFusion proxy, access the result, parse through it and create an array by splitting the string at “,”.

    Click here to download the source files.

    As a note, I am also using Grant Skinner’s GTween class and Ted Patrick’s FDOT classes. For some reason the FDOT class would not access the XML on our Dev server, but accessed the dynamic XML classes fine. FDOT would access the XML file locally…just not on our DEV server, so I am assuming it’s just sandbox issue.

    Below is the ColdFusion proxy source code:

    <cfset urlAddress_Dow="http://download.finance.yahoo.com/d/quotes.csv?s=^DJI&f=sl1d1t1c1ohgv&e=.csv" />
    <cfset urlAddress_Google="http://download.finance.yahoo.com/d/quotes.csv?s=GOOG&f=sl1d1t1c1ohgv&e=.csv" />
    
    <cfif #url.stock# is 1>
    	<cfhttp url="#urlAddress_Dow#" method="GET" resolveurl="Yes" throwOnError="Yes"/>
    <cfelseif #url.stock# is 2>
    	<cfhttp url="#urlAddress_Google#" method="GET" resolveurl="Yes" throwOnError="Yes"/>
    </cfif>
    
    <cfset stockInfo = CFHTTP.FileContent> 	
    
    <cfprocessingdirective suppresswhitespace="Yes">
    <cfcontent type="text/xml; charset=utf-16">
    
    <cfxml variable="xmlobject">
    <stocks>
    	<company>
    		<cfoutput>#stockInfo#</cfoutput>
    	</company>
    </stocks>
    </cfxml>
    
    <cfset baseStock=toString(xmlobject)>
    <cfset finalStock=replace(baseStock, "UTF-8", "utf-16")>
    
    <cfoutput>#finalStock#</cfoutput>
    
    </cfprocessingdirective>
    

    Below is the xml feed to determine what stocks to call. Also note the “stockTimer” config. This sets the time each stock is shown.

    <?xml version="1.0" encoding="UTF-8"?>
    
    <stocks>
    	<config>
    		<stockTimer>15000</stockTimer>
    	</config>
    
    	<company name="DJI">
    		<path>http://localhost:8500/stockticker_cf/stockproxy.cfm?stock=1</path>
    	</company>
    	<company name="Google">
    		<path>http://localhost:8500/stockticker_cf/stockproxy.cfm?stock=2</path>
    	</company>
    </stocks>
    

    Related Articles:

  • AS3: Adding motion blur to a Tween in Flash CS3
  • AS3, CF & AIR: Creating a static XML file for use with a StockTicker
  • AS3: Object References and Garbage Collection, by Colin Moock
  • FDOT – Trying out Ted Patrick’s collection of AS3 classes that make hard things easier.
  • AS3: More blurring in Flash CS4
  • Continue Reading

    AS3: Object References and Garbage Collection, by Colin Moock

    Posted on 27. Sep, 2009 by Brian Connatser.

    0

    This is one video out of a great series given by Colin Moock. Learn to refer to a single object from multiple parts of a program, then study the principles of memory management in ActionScript.

    Related Articles:

  • AS3: Adding motion blur to a Tween in Flash CS3
  • AS3: More blurring in Flash CS4
  • AS3: Accessing Yahoo Finance with Flash, using ColdFusion as a proxy.
  • FDOT – Trying out Ted Patrick’s collection of AS3 classes that make hard things easier.
  • Flex – AS3: Creating Custom Events
  • Continue Reading

    Hoping to go…Max 2009.

    Posted on 01. Sep, 2009 by Brian Connatser.

    0

    Continue Reading

    1 2 3 4 »
    Flash and the City banner

    Twitter: connatser

    • My MBPro now sports #RobotLegs - http://twitpic.com/17rkck about 1 hour ago from TweetDeck
    • @tcoppedge hey thanks, I still need to do that export for you :)= about 1 hour ago from TweetDeckin reply to tcoppedge
    • RT @EladElrom: Test Driven Development (#TDD) with #FlexUnit 4 - Complete tutorial, files & pres posted http://bit.ly/dhhSUD #360Flex about 1 hour ago from TweetDeck
    • @jqdaily @queencodemonkey @CurtStaubach Thanks guys :) about 2 hours ago from TweetDeckin reply to jqdaily
    • Today is my anniversary (13 years) and my wife was cool enough to let me come to #360Flex. Love you @hconnatser !! about 2 hours ago from TweetDeck

    Categories

    • ActionScript
    • Enterprise Development
    • Flex
    • Frameworks
    • Geek stuff
    • Training
    • Web and RIA

    AS3 Classes

    • AS3 Core Library
    • Base64 encoder/decoder class
    • Degrafa
    • flexlib
    • GTween
    • picasa-flex-api

    Blogroll

    • betapoint.tv
    • Blogna.org
    • CSSEdit
    • exanimo
    • F-Unit
    • Flex Learning Advisors
    • Quicksilver
    • Ribbit
    • The Photo Argus
    • Tri-Cities Adobe User Group
    • WDL – Web Design Ledger

    Development Resources

    • AS3 Design Patterns
    • CFEclipse
    • CodeIgniter
    • Eclipse
    • Oracle jDeveloper 11g
    • script.aculo.us
    • Subclipse
    • swfobject
    • Tortoise SVN
    • YUI Compressor

    © 2009 Brian Connatser – RIA Developer. All Rights Reserved.