June 8, 2009

ActionScript 3 – Dynamic Menu

Filed under: Flash, Freebies — Tags: , , , — admin @ 11:48 pm

Download Source

Here I’ll be showing you how to create a menu in Flash that creates a navigation structure from an XML file. Each button can load various types of media (images, swfs, videos) or even open a web page. We will open Flash and create a new Movie Clip called “nav” and give it the same linkage id class name. Create a a box 40px tall and convert it to a Movie Clip with the instance name of “bg”. Create a new layer and create a new dynamic text field with the instance name of “title_txt”. Make sure to embed your fonts for your desired character set. Now here is one thing I figured out that is kind of important. Create another layer on top and copy your MC called “bg” and paste it into this new layer with the instance name of “trans” and set the Alpha property to zero. This will act as our hit state. Without this the cursor loses focus when it is located over the dynamic text.

Create a class file called “BuildMenu.as”. In Flash, change your Document Class to BuildMenu. Save.

Create an XML file called “menu.xml” and fill it with these contents:

<?xml version="1.0" encoding="utf-8"?>
<navigation>
	<button title="Image" action="image1.jpg" />
	<button title="Video F4V" action="video1.f4v" />
	<button title="Video MPEG" action="video2.mpeg" />
	<button title="SWF File" action="swf1.swf" />
	<button title="Contact" action="http://www.google.com" />
</navigation>

Open BuildMenu.as and fill it with this code:

// ActionScript file
package {
	import fl.transitions.Tween;
	import fl.transitions.easing.*;
 
	import flash.display.*;
	import flash.events.*;
	import flash.net.*;
 
	public class BuildMenu extends Sprite {
 
		private var titles:Array = new Array();
		private var actions:Array = new Array();
		private var total:uint = 0;
		private var xmlFile:String = "menu.xml";
		private var loadMenuXML:URLLoader = new URLLoader();
		private var fadeSpeed:Number = 0.2;
 
		public function BuildMenu() {
 
			var reqMenuXML:URLRequest = new URLRequest(xmlFile);
 
			loadMenuXML.addEventListener(Event.COMPLETE, parseXML);
			loadMenuXML.load(reqMenuXML);
		}
 
		private function parseXML(e:Event):void {
			var menuXML:XML = new XML(loadMenuXML.data);
 
			var container:Sprite = new Sprite();
			container.name = "container";
			container.x = 100;
			addChild(container);
 
			for (var i:int = 0; i<menuXML.*.length(); i++) {
				titles.push(menuXML.button[i].@title);
				actions.push(menuXML.button[i].@action);
				var btn:MovieClip = new nav;
				container.addChild(btn);
				btn.y = i*40;
				btn.title_txt.htmlText = titles[i];
				btn.trans.addEventListener(MouseEvent.CLICK, navClick);
				btn.trans.addEventListener(MouseEvent.ROLL_OVER, fadeDown);
				btn.trans.addEventListener(MouseEvent.ROLL_OUT, fadeUp);
				btn.trans.buttonMode = true;
				btn.trans.ID = i;
			}
 
		}
 
		private function fadeDown(e:Event):void {
			var fDown:Tween = new Tween(e.currentTarget.parent.bg, "alpha", None.easeOut, e.currentTarget.parent.bg.alpha, 0.5, fadeSpeed, true);
		}
		private function fadeUp(e:Event):void {
			var fUp:Tween = new Tween(e.currentTarget.parent.bg, "alpha", None.easeOut, e.currentTarget.parent.bg.alpha, 1, fadeSpeed, true);
		}
		private function navClick(e:Event):void {
			determineLink(e.currentTarget.ID);
		}
 
		private function determineLink(id) {
			//trace(titles[id]+" -> "+actions[id]);
			var actionItem:String = actions[id].toString();
			// Find file extension
			var fileExtension:String = actionItem.substr(0,4);
			if (fileExtension == "http") {
				// this is a URL
			} else {
				fileExtension = actionItem.substr(actionItem.lastIndexOf('.')+1, actionItem.length);
				// this is a file extension
			}
			var mediaType:String = fileExtension.toLowerCase();
			switch (mediaType) {
				case "http":
				trace("Open URL -> "+actionItem);
				openURL(actionItem);
				break;
				case "flv":
				case "f4v":
				case "mov":
				case "mpeg":
				case "mp4":
				trace("Load video -> "+actionItem);
				loadVideo(actionItem);
				break;
				case "jpg":
				case "gif":
				case "jpeg":
				case "png":
				trace("Load image -> "+actionItem);
				loadImage(actionItem);
				break;
				case "swf":
				trace("Load swf -> "+actionItem);
				loadSWF(actionItem);
				break;
				default :
				trace("Incorrect file type used");
				break;
			}
		}
 
		private function loadImage(file) {
			// load Image
			var assetLoader:Loader = new Loader();
			addChild(assetLoader);
			assetLoader.load(new URLRequest(file));	
		}
 
		private function loadSWF(file) {
			// load SWF
			var assetLoader:Loader = new Loader();
			addChild(assetLoader);
			assetLoader.load(new URLRequest(file));
		}
 
		private function loadVideo(file) {
			// load Video
		}
 
		private function openURL(url) {
			// open URL
			var loadURL:URLRequest = new URLRequest(url);
			try {
				navigateToURL(loadURL, "_blank");
			} catch (e:Error) {
				trace("Cannot load -> "+url);
			}
		}
	}
}

To view the output, Test Movie in Flash.

February 9, 2009

Freebie: ActionScript 3 – Flash text using XML & CSS

Filed under: Flash, Freebies — Tags: , , , , , — admin @ 4:39 pm

Download Source

Ok, so I’m a little behind the curve in AS3 right now. But I’ve gotta get learning because I see a lot of AIR apps and other AS3 apps I need to build in the future. I’ve a had a little spare time today to follow Colin Moock’s Essential AS3 book. I’ve made it a goal to create a file that uses an ActionScript 3 class to load external text stored in an XML file that is styled with a CSS file.

myText.xml

<?xml version="1.0" encoding="utf-8"?>
<MYTEXT>
	<TEXT><![CDATA[<p><span class='bigText'>This is my title</span></p><br /><p><b>Bold</b>, <i>italics</i>, <u>underline</u>, normal</p><br /><p><a href='http://www.google.com/'>Web link</a></p><br /><p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque facilisis, metus ut commodo tempus, enim mi placerat justo, nec ornare sapien urna eu nisl. In hac habitasse platea dictumst. Integer suscipit, nisl id consectetur pharetra, velit quam accumsan diam, sit amet commodo nibh libero vitae neque. Donec neque dui, ultrices id, condimentum in, eleifend non, odio. Sed elit risus, hendrerit at, gravida quis, porttitor a, nisi. Pellentesque ullamcorper. Nulla facilisi. Maecenas sagittis. Phasellus nulla ipsum, varius non, bibendum vel, sollicitudin ac, nunc.</p><p>Integer id tortor sit amet odio fermentum dictum. Integer metus arcu, laoreet non, lobortis et, tincidunt sed, erat. Quisque porttitor nibh ac felis. Donec facilisis, purus sed eleifend dapibus, quam est ultrices turpis, vel dictum justo lectus ac ligula. Nullam diam tortor, suscipit sodales, porta at, vestibulum venenatis, ipsum. Nunc placerat, urna eu elementum dictum, odio metus lobortis justo, sit amet convallis lacus mauris sed sem.</p>]]></TEXT>
</MYTEXT>

styles.css

p {
	font-family: Arial;
	font-size: 12px;
	color: #006600;
}
.bigText {
	font-family: Arial;
	font-size: 24px;
	color: #0099FF;
	letter-spacing:-1px;
}
a {
	color:#FF0000;
	text-decoration:none;
}
a:hover {
	color:#0000FF;
	text-decoration:underline;
}

CSS_XML.as

package {
	import flash.display.*;
	import flash.text.*;
	import flash.events.*;
	import flash.net.*;
 
	public class CSS_XML extends Sprite {
 
		private var myText:XML;		
		private var urlLoaderXML:URLLoader;
		private var paragraph:String;
		private var CSSFile:String = "styles.css";
		private var XMLFile:String = "myText.xml";
 
		public function CSS_XML() {
			var urlRequest:URLRequest = new URLRequest(XMLFile);
			urlLoaderXML = new URLLoader();
			urlLoaderXML.addEventListener(Event.COMPLETE, completeListenerXML);
			urlLoaderXML.load(urlRequest);
		}	
 
		private function completeListenerXML(e:Event):void {
			myText = new XML(urlLoaderXML.data);
			paragraph = myText.TEXT.toString();
			loadCSS();
		}
 
		private function loadCSS() {
			var urlLoaderCSS:URLLoader = new URLLoader();
			urlLoaderCSS.addEventListener(Event.COMPLETE, completeListenerCSS);
			urlLoaderCSS.load(new URLRequest(CSSFile));
		}
 
		private function completeListenerCSS(e:Event):void {
			var styleSheet:StyleSheet = new StyleSheet();
			styleSheet.parseCSS(e.target.data);
			var t:TextField = new TextField();
			t.multiline = true
			t.autoSize = TextFieldAutoSize.LEFT;
			t.width = 550;
			t.wordWrap = true;
			t.styleSheet = styleSheet;
			t.htmlText = paragraph;
 
			addChild(t);
		}
	}
}

Now the end-result isn’t amazing-looking. It definitely needs a scrolling utility, but it’s a good start.

Enjoy!

October 7, 2008

Freebie: Dynamic Flash Video Player

Filed under: Flash, Freebies, Video — Tags: , , — admin @ 9:51 pm

Download Source

Download includes versions for 4×3 and 16×9 aspect ratios.

This content requires Adobe Flash Player 8

Download Adobe Flash

I’ve created a video player that you can use for free that is easily customizable. The cool thing is you don’t need to open Flash to change the video you want it to display. Just write is as a variable in your embed code like this:

<script type="text/javascript" language="javascript">
        var so = new SWFObject("/examples/videoplayer/video_4x3.swf", "mymovie", "500", "405", "8", "#000000");
            so.addParam("menu", "false");
			so.addParam("scale", "noscale");
			so.addParam("allowFullScreen", "true");
			so.addVariable("myVideo", "vid1.flv");
            so.write("flash");
    </script>

Note so.addVariable(“myVideo”, “vid1.flv”); All you need to do is change vid1.flv to the video of your choice.

Enjoy!

October 2, 2008

Fullscreen background images in Flash

Filed under: Flash, Freebies — Tags: , , , , — admin @ 12:38 am

Here’s a freebie – Flash source code to use fullscreen scaling images that maintain their aspect ration when scaling (AS2). I am using smoothImageLoad to convert the loaded png, jpg or gif to a smooth bitmap. Enjoy!

Download Source View Example

// Use Tween class to fade in the image
import mx.transitions.Tween;
import mx.transitions.easing.*;
 
var stageListener:Object=new Object();
stageListener.onResize=function(){
	position();
};
 
Stage.align="TL";
Stage.scaleMode="noScale";
Stage.addListener(stageListener);
 
// Reposition objects when the movie is resized
function position() {
	// Find new value of stage size
	var W:Number = Stage.width;
	var H:Number = Stage.height;
	// Find center of stage
	var centerX:Number = W/2;
	var centerY:Number = H/2;
	// Center main bg clip
	background_mc._x = centerX;
	background_mc._y = centerY;
	// Center target clip inside the main bg clip
	background_mc.target_mc._x = -_global.BGW/2;
	background_mc.target_mc._y = -_global.BGH/2;
	var imageRatio:Number;
	var imageXRatio = W/_global.BGW;
	var imageYRatio = H/_global.BGH;
	// Determine if the width is larger than the height
	if (imageXRatio&gt;imageYRatio) {
		imageRatio = imageXRatio;
	} else {
		imageRatio = imageYRatio;
	}
	// Scale the image to fit fullscreen
	background_mc._xscale = background_mc._yscale=imageRatio*100;
}
 
// Function for smoothing resizable bitmaps
function smoothImageLoad(imgURL, targetMovie) {
	var i = 0;
	do {
		i++;
	} while (eval("_root.smoothImageLoadTemp"+i) != undefined);
	tmc = targetMovie.createEmptyMovieClip("smoothImageLoadTemp"+i, targetMovie.getNextHighestDepth());
	tmc.createEmptyMovieClip("ti",tmc.getNextHighestDepth());
	tmc.tm = targetMovie;
	with (tmc) {
		tmcl = new MovieClipLoader();
		tmcl.onLoadComplete = function() {
			var fadeBG:Tween = new Tween(targetMovie, "_alpha", None.easeOut, 0, 100, 1, true);
			ti.onEnterFrame = function() {
				pixelData = new flash.display.BitmapData(ti._width, ti._height);
				_global.BGW = ti._width;
				_global.BGH = ti._height;
				pixelData.draw(ti);
				tm.attachBitmap(pixelData,1,true,true);
				tm.smoothImageLoadComplete();
				_parent._parent._parent.position();
				removeMovieClip(ti._parent);
			};
		};
		tmcl.loadClip(imgURL,tmc.ti);
	}
}
// Load your image
smoothImageLoad("image.jpg",background_mc.target_mc);

© 2010 Aaron Benson. All rights reserved.

Powered by WordPress