ActionScript 3 AS3:创建渐变矩形

/****************************
Import Classes
****************************/
import flash.display.*;
import flash.geom.*;

/****************************
Define Variables
****************************/
//Type of Gradient we will be using
var fType:String = GradientType.LINEAR;
//Colors of our gradient in the form of an array
var colors:Array = [ 0xF1F1F1, 0x666666 ];
//Store the Alpha Values in the form of an array
var alphas:Array = [ 1, 1 ];
//Array of color distribution ratios.  
//The value defines percentage of the width where the color is sampled at 100%
var ratios:Array = [ 0, 255 ];
//Create a Matrix instance and assign the Gradient Box
var matr:Matrix = new Matrix();
    matr.createGradientBox( 200, 20, 0, 0, 0 );
//SpreadMethod will define how the gradient is spread. Note!!! Flash uses CONSTANTS to represent String literals
var sprMethod:String = SpreadMethod.PAD;
//Start the Gradietn and pass our variables to it
var sprite:Sprite = new Sprite();
//Save typing + increase performance through local reference to a Graphics object
var g:Graphics = sprite.graphics;
    g.beginGradientFill( fType, colors, alphas, ratios, matr, sprMethod );
    g.drawRect( 0, 0, 400, 200 );

addChild( sprite );

ActionScript 3 获取嵌入SWF的页面的URL

function get currentURL():String
{
    var url:String;
    if (ExternalInterface.available) {
        return ExternalInterface.call("window.location.href");
    }
    return url;
}

ActionScript 3 在弧度和度数之间转换

function degrees(radians:Number):Number
{
    return radians * 180/Math.PI;
}

function radians(degrees:Number):Number
{
    return degrees * Math.PI / 180;
}

ActionScript 3 Slugify

function slugify(string:String):String
{
    const pattern1:RegExp = /[^\w- ]/g; // Matches anything except word characters, space and -
    const pattern2:RegExp = / +/g; // Matches one or more space characters
    var s:String = string;
    return s.replace(pattern1, "").replace(pattern2, "-").toLowerCase();
}

ActionScript 3 使用ActionScript 3异步读取文件

// Imports
      import flash.filesystem.FileMode;
      import flash.filesystem.FileStream;
      import flash.filesystem.File;
      import flash.events.ProgressEvent;
      import flash.events.Event;
       
      // Declare the FileStream and String variables

      private var _fileStream:FileStream;
 
      private var _fileContents:String;
       
      private function onCreationComplete():void // Fired when the application has been created

      {

      var myFile:File = File.appResourceDirectory; // Create out file object and tell our File Object where to look for the file

      myFile = myFile.resolve("mySampleFile.txt"); // Point it to an actual file


      _fileStream = new FileStream(); // Create our file stream

      _fileStream.addEventListener(ProgressEvent.PROGRESS, onFileProgress); // Add our the progress event listener

      _fileStream.addEventListener(Event.COMPLETE, onFileComplete); // Add our the complete event listener
       
      _fileStream.openAsync(myFile, FileMode.READ); // Call the openAsync() method instead of open()

      }
      private function onFileProgress(p_evt:ProgressEvent):void // Event handler for the PROGRESS Event
      {
      _fileContents += _fileStream.readMultiByte(_fileStream.bytesAvailable, "iso-8859-1"); // Read the contens of the file and add to the contents variable
       
      fileContents_txt.text = _fileContents; // Display the contents. I've created a TextArea on the stage for display
      }
       
      private function onFileComplete(p_evt:Event):void // Event handler for the COMPLETE event

      {
      _fileStream.close(); // Clean up and close the file stream
      }

ActionScript 3 AS3:基本计时器示例

var timer:Timer = new Timer(1000, 2);
    timer.addEventListener(TimerEvent.TIMER, blah);
    timer.start();

function blah(e:TimerEvent):void{
     trace("Times Fired: " + e.currentTarget.currentCount);
     trace("Time Delayed: " + e.currentTarget.delay);
}

ActionScript 3 AS3:我最喜欢的助手功能

public function SlideShow( ){
     //If you are working locally on your computer, you will load manually load the xml file.  Otherwise you will be receiving the xml file from SWFObject2
     xmlURL = ( getDevelopmentMode() === "Production" ) ? getFlashVars().xml : "./xml/data.xml";

     //Capture where the SWF is living on the live site
     var currentLocationOfSWF:String = getContextPath();
}

private function getFlashVars():Object
{
     return Object( LoaderInfo( this.loaderInfo ).parameters );
}

private function getDevelopmentMode():String
{
	var dev:Boolean = new RegExp("file://").test( this.loaderInfo.loaderURL);

	if( dev ) return "Development";
	else return "Production";
}

private function getContextPath():String
{
	var uri:String = getLoaderURL();
	return uri.substring(0, uri.lastIndexOf("/")) + "/";
}

private function getLoaderURL():String
{
	return this.loaderInfo.loaderURL;
}

ActionScript 3 AS3:使用POST发送数据

var bg_mc:MovieClip = new MovieClip();
	bg_mc.graphics.beginFill(0xFF0000, 1);
	bg_mc.graphics.drawRect(0, 0, 100, 100);
	bg_mc.graphics.endFill();
	bg_mc.x = stage.stageWidth / 2 - bg_mc.width / 2;
	bg_mc.y = stage.stageHeight / 2 - bg_mc.height / 2 ;
	bg_mc.buttonMode = true;
	bg_mc.addEventListener(MouseEvent.MOUSE_DOWN, visitSite);
addChild(bg_mc);

function visitSite(e:MouseEvent):void {
	var url:String = "http://api.flickr.com/services/rest/";
	var request:URLRequest = new URLRequest(url);
	var requestVars:URLVariables = new URLVariables();
		requestVars.api_key = "3c84c0ca7f9ae17842a370a3fbc90b63";
		requestVars.method = "flickr.test.echo";
		requestVars.format = "rest";
		requestVars.foo = "bar";
		requestVars.sessionTime = new Date().getTime();
		request.data = requestVars;
		request.method = URLRequestMethod.POST;
	
	var urlLoader:URLLoader = new URLLoader();
		urlLoader = new URLLoader();
		urlLoader.dataFormat = URLLoaderDataFormat.TEXT;
		urlLoader.addEventListener(Event.COMPLETE, loaderCompleteHandler, false, 0, true);
		urlLoader.addEventListener(HTTPStatusEvent.HTTP_STATUS, httpStatusHandler, false, 0, true);
		urlLoader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler, false, 0, true);
		urlLoader.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler, false, 0, true);
	for (var prop:String in requestVars) {
		//trace("Sent: " + prop + " is: " + requestVars[prop]);
	}
	try {
		urlLoader.load(request);
	} catch (e:Error) {
		trace(e);
	}
}
function loaderCompleteHandler(e:Event):void {
	var responseVars = URLVariables( e.target.data );
	trace( "responseVars: " + responseVars );
	
}
function httpStatusHandler( e:HTTPStatusEvent ):void {
	//trace("httpStatusHandler:" + e);
}
function securityErrorHandler( e:SecurityErrorEvent ):void {
	trace("securityErrorHandler:" + e);
}
function ioErrorHandler( e:IOErrorEvent ):void {
	//trace("ORNLoader:ioErrorHandler: " + e);
	dispatchEvent( e );
}

ActionScript 3 AS3:使用加载程序进行SWF,JPEG,GIF和PNG

/********************************
Event Listeners
********************************/
var imgLoader:Loader = new Loader();
	initBasicListeners( imgLoader );
	imgLoader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, progressHandler, false, 0, true);
	imgLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, onCompleteHandler, false, 0, true);
	imgLoader.load(new URLRequest(asset));

//These Event Listeners are used a lot so let's try to minimize redundancies
function initBasicListeners(dispatcher:IEventDispatcher):void
{
	dispatcher.addEventListener(HTTPStatusEvent.HTTP_STATUS, httpStatusHandler, false, 0, true);
	dispatcher.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler, false, 0, true);	
	dispatcher.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler, false, 0, true);
}

/********************************
Event Handlers
********************************/
function httpStatusHandler (e:Event):void
{
	//trace("httpStatusHandler:" + e);
}
function securityErrorHandler (e:Event):void
{
	trace("securityErrorHandler:" + e);
}
function ioErrorHandler(e:Event):void
{
	trace("ioErrorHandler: " + e);
}
function progressHandler(e:Event):void
{
	trace(e.currentTarget.bytesLoaded + " / " + e.currentTarget.bytesTotal);
}

function onCompleteHandler (e:Event):void
{
	trace("imgCompleteHandler:" + e.currentTarget.content + " "  + e.currentTarget.loader);
	addChild( e.currentTarget.loader );
}

ActionScript 3 AS3:正则表达式基础

//Using Replace
var toungeTwister:String = "Peter Piper Picked a peck of pickled peppers";
//g is a global identifier so it doesn't stop only on the first match
var pickRegExp:RegExp = /pick|peck/g;
var replaced:String = toungeTwister.replace( pickRegExp, "Match");
//trace(replaced);

//Using Character Classes
var compassPoints:String = "Naughty Naotersn elephants squirt water";
var firstWordRegExp:RegExp = /N(a|o)/g;
//trace( compassPoints.replace( firstWordRegExp, "MATCH" ) );
													   
var favoriteFruit = "bananas";
var bananaRegExp:RegExp = /b(an)+a/;
//trace( bananaRegExp.test( favoriteFruit ) );

//Exec() method returns an Object containing the groups that were matched
var htmlText:String = "<strong>This text is important</strong> while this text is not as important <strong>ya</strong>";
var strongRegExp:RegExp = /<strong>(.*?)<\/strong>/g;
var matches:Object = strongRegExp.exec( htmlText);
for( var i:String in matches ) {
	//trace( i + ": " + matches[i] );
}

var email:String = "c@chrisaiv.comm";
var emailRegExp:RegExp = /^([a-zA-Z0-9_-]+)@([a-zA-Z0-9.-]+)\.([a-zA-Z]{2,4})$/i;
var catches:Object = emailRegExp.exec( email );
for( var j:String in catches ) {
	//trace( j + ": " + catches[j] );
}
//trace( "This e-mail's validity is: " + emailRegExp.test( email ) );

//Test the validity of an e-mail
var validEmailRegExp:RegExp = /([a-z0-9._-]+)@([a-z0-9.-]+)\.([a-z]{2,4})/;
trace( validEmailRegExp.test( "a1a@c.info" ) );


//Return a Boolean if there is a pattern match
var phoneNumberPattern:RegExp = /\d\d\d-\d\d\d-\d\d\d\d/; 
trace( phoneNumberPattern.test( "347-555-5555" )); //true 
trace( phoneNumberPattern.test("Call 800-123-4567 now!")); //true 
trace( phoneNumberPattern.test("Call now!")); //false 

//Return the index number of the occurence is there is a pattern match
var themTharHills:String = "hillshillshillsGOLDhills"; 
trace(themTharHills.search(/gold/i)); //15