Not just Actionscript noodlings

08 Jul

Font Repository


I have always found that when programming large sites, controlling fonts becomes problematic. Not having a central font repository made maintaining and changing fonts a struggle.

So I created my own font area, a single point of contact for all my fonts – being a single point of contact it makes sense to make it a Singleton class. It uses getter function which hold the TextFormat information.

If you use, say, the same format over 5 different classes throughout your site,you now only have to change it in one place, rather than 5.

 
//
//    FontHandler - font repository
//
package com.fourteenlox.utils
{
 import flash.text.*;
 
public class FontHandler
{
 private static var     _instance:FontHandler;
 
 public function FontHandler(singletonEnforcer:SingletonEnforcer) {}
 
 public static function getInstance():FontHandler
 {
   if(FontHandler._instance == null)
   {
   FontHandler._instance = new FontHandler(new SingletonEnforcer())
   }
   return FontHandler._instance;
  }
 
 public function get bodyformat():TextFormat
 {
  var _bodyformat:TextFormat       = new TextFormat;
  _bodyformat.size                       = 14;
  _bodyformat.font                      = new HelMed ().fontName;
  _bodyformat.color                     = 0x777777;
  _bodyformat.align                     = 'left';
  return _bodyformat;
  }
 
  public function get titleformat():TextFormat
  {
  var _titleformat:TextFormat     = new TextFormat;
  _titleformat.size                     = 24;
  _titleformat.font                    = new HelMed ().fontName;
  _titleformat.color                   = 0xFF0000;
  _titleformat.align                     = 'left';
  return _titleformat;
  }
 
  public function get linkformat():TextFormat
  {
  var _linkformat:TextFormat      = new TextFormat;
  _linkformat.size                     = 14;
  _linkformat.font                     = new HelMed ().fontName;
  _linkformat.color                     = 0x000000;
  _linkformat.align                     = 'left';
  _linkformat.underline                = true;
  return _linkformat;
  }
 }
}
class SingletonEnforcer{}

Usage:

 
import com.fourteenlox.utils.FontHandler;
 
_textTitle			        = new TextField();
_textTitle.embedFonts 		= true;
_textTitle.defaultTextFormat 	= FontHandler.getInstance().titleformat;
_textTitle.antiAliasType 	= AntiAliasType.ADVANCED;
_textTitle.autoSize 		= TextFieldAutoSize.LEFT;
_textTitle.multiline 		= true;
_textTitle.wordWrap		= true;
_textTitle.selectable 		= false;
_textTitle.width		        = 700;
_textTitle.text 		        = _xml.text.@title;
addChild(_textTitle);

Grrrrr, can’t work out how to line up the code, it seems to break when I paste it here….


05 Jul

Which loader?


I just found this useful peice of infomation from LiveDocs:

The Loader class is used to load SWF files or image (JPG, PNG, or GIF) files.

Use the URLLoader class to load text or binary data.

The URLLoader class downloads data from a URL as text, binary data, or URL-encoded variables. It is useful for downloading text files, XML, or other information to be used in a dynamic, data-driven application.

I was unaware until now that using URLLoader to load XML data was the preferred option, now to go back through some projects and make the change.


02 Jul

Is a number even or odd?


It’s very easy to work that out. You just need to use the Modulus function (%).

var isEven:Boolean = ((num % 2) == 0);

credit: bit-101


02 Jul

Find which face is clicked on a Papervision3D Cube.


Firstly you need to add an Event Listener to your Cube.

cube.addEventListener(InteractiveScene3DEvent.OBJECT_PRESS, onClickHandler);

Inside the onClickHandler is the function for determining which face is being clicked on. I have only included the front and back in the switch case, but you can also have “top”, “bottom”, “right” and “left”.

private function onClickHandler(event:InteractiveScene3DEvent):void 
		{ 			
			var face:String = faceHandler(event);
 
			switch (face)
			{				
				case "front" : 
					// Do something when the front is clicked
				break;
 
				case "back" : 
					// Do something when the back is clicked
				break;
			}
		}

Here is the faceHandler function. It uses the InteractiveUtils.getMapCoordAtPoint Papervision function to determine which face is being clicked on.

private function faceHandler(event:InteractiveScene3DEvent):String
		{
			var faceNormals = { back:new Number3D(0,0,1), front:new Number3D(0,0,-1), right:new Number3D(1,0,0), left:new Number3D(-1,0,0),bottom:new Number3D(0,-1,0), top:new Number3D(0,1,0)}; 
 
			var point:Object = 
			InteractiveUtils.getMapCoordAtPoint(event.face3d, event.sprite.mouseX, event.sprite.mouseY); 
 
			for(var key:String in faceNormals) 
			{ 
				if ( Number3D.dot(faceNormals[key], event.face3d.faceNormal) > 0.99 )  return key; 
			} 
			return "none"; 
		}

I can’t take credit for the initial code (I can’t find where I got it, to credit them) – however i have edited it and expanded the functionality.


01 Jun

Contact Form


Created a contact form class as I needed it for several sites and thought I’d share it…Its a very simple contact form, with required fields and email validation. No POP3 server needed.

Download the Contact Form.zipView example

Usage:

import ContactForm;
 
var contactForm = new ContactForm("emailaddresstosendto@example.com", "Email from our web site");
addChild(contactForm);

Contact Form Class

package 
{
	import flash.display.Sprite;
	import flash.display.Loader;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	import flash.text.TextField;
	import flash.text.TextFormat;
	import flash.text.AntiAliasType;
	import flash.text.TextFieldAutoSize;
	import flash.text.TextFieldType;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.events.TimerEvent;
	import flash.net.URLVariables;
	import flash.net.URLLoaderDataFormat;
	import flash.net.URLRequestMethod;
	import flash.utils.Timer;
 
	public class ContactForm extends Sprite 
	{
		// constants
		private const SENDMAILURLREQ:URLRequest				= new URLRequest("ContactFormSendForm.php");  		
 
		private const SENDBTN:String						= "SEND";  
		private const NAME:String							= "Name :";   
		private const EMAIL:String							= "Email :";  
		private const MESSAGE:String						= "Message :";  		
		private const NOTVALIDEMAIL:String					= "Not a valid email address";
		private const ALLFIELDS:String						= "All fields are required";
		private const SENDING:String						= "Sending...";
		private const ERRORTEXT:String						= "An error has occurred please try again";
		private const MESSAGESENT:String					= "Thanks, your message has been sent";
		private const absoluteURL:String					= "";
 
		// variables			
		private var _txtName:TextField 						= new TextField ();
		private var _txtMessage:TextField 					= new TextField ();
		private var _txtEmail:TextField 					= new TextField ();
		private var _txtSend:TextField 						= new TextField ();      
		private var _inputName:TextField 					= new TextField ();
		private var _inputMessage:TextField 				= new TextField ();
		private var _inputEmail:TextField 					= new TextField ();
		private var _txtInfo:TextField 						= new TextField ();
		private var _timer:Timer;
		private var _emailToSendTo:String;   
		private var _emailSubject:String;;   
 
		public function ContactForm (_emailToSendTo, _emailSubject) 
		{
			// init() is triggered once its added to the stage, weak referenced to help memory.
			addEventListener(Event.ADDED_TO_STAGE, init, false, 0, true);
 
			this._emailToSendTo			= _emailToSendTo;
			this._emailSubject 			= _emailSubject
		}
 
		private function init(event:Event):void 
		{
			// remove listener
			removeEventListener(Event.ADDED_TO_STAGE,init);
 
			// setup texts and formats
			setupTexts();
		}
 
		private function setupTexts ():void 
		{
			// setup formats
			var _format:TextFormat 				= new TextFormat (); 
			_format.size 						= 12;
			_format.font 						= 'Arial';
			_format.color 						= 0x333333;
			_format.align 						= 'left';    
 
			var _infoformat:TextFormat 			= new TextFormat (); 
			_infoformat.size 					= 12;
			_infoformat.font 					= 'Arial';
			_infoformat.color 					= 0xFF0000;
			_infoformat.align 					= 'left';  
 
			var _btnformat:TextFormat 			= new TextFormat (); 
			_btnformat.size 					= 12;
			_btnformat.font 					= 'Arial';
			_btnformat.color 					= 0xFFFFFF;
			_btnformat.align 					= 'left'; 
 
			// setup texts and tex tboxes
			_txtInfo.defaultTextFormat 			= _infoformat;            
			_txtInfo.antiAliasType 				= AntiAliasType.ADVANCED;
			_txtInfo.autoSize 					= TextFieldAutoSize.LEFT;
			_txtInfo.wordWrap 					= true;
			_txtInfo.multiline 					= true;
			_txtInfo.selectable 				= false; 
			_txtInfo.text 						= "";
			_txtInfo.x 							= 10;
			_txtInfo.y 							= 10;   
			_txtInfo.width 						= 400;
			addChild(_txtInfo);
 
			_txtName.defaultTextFormat			= _format;   
			_txtName.antiAliasType 				= AntiAliasType.ADVANCED;
			_txtName.autoSize 					= TextFieldAutoSize.LEFT;
			_txtName.wordWrap 					= true;
			_txtName.multiline 					= true;
			_txtName.selectable 				= false; 
			_txtName.text 						= NAME;
			_txtName.x 							= 10;
			_txtName.y 							= _txtInfo.y + _txtInfo.height + 30;
			addChild(_txtName);
 
			_inputName.defaultTextFormat 		= _format;      
			_inputName.text 					= "";
			_inputName.width 					= 200;         
			_inputName.height 					= 20;
			_inputName.x 						= _txtName.x + _txtName.width + 10;
			_inputName.y 						= _txtName.y;
			_inputName.border 					= true;
			_inputName.type 					= TextFieldType.INPUT;
			addChild(_inputName); 
 
			_txtEmail.defaultTextFormat 		= _format;            
			_txtEmail.antiAliasType 			= AntiAliasType.ADVANCED;
			_txtEmail.autoSize 					= TextFieldAutoSize.LEFT;
			_txtEmail.wordWrap 					= true;
			_txtEmail.multiline 				= true;
			_txtEmail.selectable 				= false;    
			_txtEmail.text 						= EMAIL;
			_txtEmail.x 						= 10;
			_txtEmail.y 						= _txtName.y + _txtName.height + 10;         
			addChild(_txtEmail);
 
			_inputEmail.defaultTextFormat 		= _format;    
			_inputEmail.text 					= "";
			_inputEmail.width 					= 200;      
			_inputEmail.height 					= 20;
			_inputEmail.x 						= _txtEmail.x + _txtEmail.width + 10;
			_inputEmail.y 						= _txtEmail.y;
			_inputEmail.border 					= true;
			_inputEmail.type 					= TextFieldType.INPUT;
			addChild(_inputEmail);  
 
			_txtMessage.defaultTextFormat 		= _format;      
			_txtMessage.antiAliasType 			= AntiAliasType.ADVANCED;
			_txtMessage.autoSize 				= TextFieldAutoSize.LEFT;
			_txtMessage.wordWrap 				= true;
			_txtMessage.multiline 				= true;
			_txtMessage.selectable 				= false;  
			_txtMessage.text					= MESSAGE;
			_txtMessage.x 						= 10;
			_txtMessage.y 						= _txtEmail.y + _txtEmail.height + 20;         
			addChild(_txtMessage);
 
			_inputMessage.defaultTextFormat 	= _format;        
			_inputMessage.text 					= "";
			_inputMessage.width 				= 200;            
			_inputMessage.height 				= 150;
			_inputMessage.x 					= _txtMessage.x + _txtMessage.width + 10;
			_inputMessage.y 					= _txtMessage.y;
			_inputMessage.border 				= true;
			_inputMessage.type 					= TextFieldType.INPUT;            
			_inputMessage.multiline 			= true;
			_inputMessage.wordWrap 				= true
			addChild(_inputMessage);           
 
			// this draws the submit button
			var _submitBtn:Sprite 				= new Sprite(); 
			_submitBtn.graphics.beginFill (0x333333);
			_submitBtn.graphics.drawRect (_txtMessage.x + _txtMessage.width + 10, _inputMessage.y + _inputMessage.height + 20, 100, 25);
			_submitBtn.graphics.endFill ();
			_submitBtn.buttonMode 				= true;
			_submitBtn.useHandCursor 			= true;
			_submitBtn.mouseChildren 			= false;
			_submitBtn.addEventListener(MouseEvent.MOUSE_DOWN, buttonHandler);
			addChild(_submitBtn);            
 
			_txtSend.defaultTextFormat 			= _btnformat;            
			_txtSend.antiAliasType 				= AntiAliasType.ADVANCED;
			_txtSend.autoSize 					= TextFieldAutoSize.LEFT;
			_txtSend.wordWrap 					= true;
			_txtSend.multiline 					= true;
			_txtSend.selectable 				= false; 
			_txtSend.text 						= SENDBTN;
			_txtSend.x = _txtMessage.x + _txtMessage.width + 40;
			_txtSend.y = _inputMessage.y + _inputMessage.height + 23;      
			_submitBtn.addChild(_txtSend);
		}
 
		private function buttonHandler(event:MouseEvent):void
		{
			// assign inputted text
			var _name:String 		= _inputName.text; 
			var _message:String 	= _inputMessage.text;
			var _email:String 		= _inputEmail.text;
 
			// Check if all the required fields have text
			if(checkRequiredFields(_name, _message, _email))
			{ 
				// Check if the Email entered is a valid one
				if (isValidEmail(_email)) sendMessage(_name, _message, _email);
 
				else _txtInfo.text = NOTVALIDEMAIL;
			}
			else
			{
				_txtInfo.text = ALLFIELDS;
			}
		}
 
		private function checkRequiredFields(__name:String, __message:String, __email:String):Boolean
		{
			// this just checks that something has been entered into the three input boxes
			if(__name!="" && __message!="" && __email!="") return true;
 
			else return false;
		}
 
		private function isValidEmail(email:String):Boolean 
		{
			// if email is not valid return false
			var emailExpression:RegExp = /^[a-z][\w.-]+@\w[\w.-]+\.[\w.-]*[a-z][a-z]$/i;
 
			return emailExpression.test(email);
		}
 
		private function sendMessage(___name:String, ___message:String, ___email:String):void
		{
			var variables:URLVariables				= new URLVariables();
			variables.abs_url						= absoluteURL;
			variables.name 							= ___name;
			variables.message						= ___message;
			variables.email 						= ___email;
			variables.send_email					= _emailToSendTo;
			variables.subject						= _emailSubject;
 
			SENDMAILURLREQ.method					= URLRequestMethod.POST;
			SENDMAILURLREQ.data						= variables;
 
			var loader:URLLoader					= new URLLoader();
			loader.dataFormat						= URLLoaderDataFormat.VARIABLES;
 
			// listens for the COMPLETE event, which means the message has been sent
			loader.addEventListener(Event.COMPLETE, messageSent)
 
			// try and send it...
			try 
			{
				_txtInfo.text = SENDING
				loader.load(SENDMAILURLREQ);
			} 
			catch (error:Error) 
			{
				_txtInfo.text = ERRORTEXT;
			}
		}	
 
		private function messageSent(event:Event):void
		{
			var loader:URLLoader					= URLLoader(event.target);
			var vars:URLVariables					= new URLVariables(loader.data);
 
			// answer is returned from the php
			if(vars.answer == "ok")
			{
				_txtInfo.text = MESSAGESENT;
 
				// this is only for looks, after the message is sent, the timer waits 4 seconds then resets the texts and inputs
				_timer=new Timer(4000,1);
				_timer.addEventListener(TimerEvent.TIMER,resetAll);
				_timer.start();
			}
			else
			{
				_txtInfo.text = ERRORTEXT;
			}
		}
 
		private function resetAll(event:TimerEvent):void
		{
			_timer.removeEventListener(TimerEvent.TIMER,resetAll);
 
			_txtInfo.text 					= "";
			_inputName.text 				= "";
			_inputEmail.text 				= "";
			_inputMessage.text 				= "";
		}
	}
}

ContactFormSendForm.php

<?php
    $sendTo   = $_POST["send_email"];
    $subject  = $_POST["subject"]; 
 
    $headers  = "From: " . $_POST["name"] ."<" . $_POST["email"] .">\r\n";
 
    $message  = "";
    $message .= "Name: ";
    $message .= "\n";
    $message .= $_POST["name"];
    $message .= "\n\n";
    $message .= "From: ";
    $message .= "\n";
    $message .= $_POST["email"];
    $message .= "\n\n";
    $message .= "\n\n";
    $message .= "Message: ";
    $message .= "\n";
    $message .= $_POST["message"];
    $message .= "\n\n";
 
 
    if(@mail($sendTo, $subject, $message, $headers))
    {
        $answer='ok';
        echo "answer=".$answer;
    }
    else
    {
        $answer='error';
        echo "answer=".$answer;
    }
?>

23 May

Creating gradient background


If you’ve ever wanted to create a block of filled colour with a gradient for a background, similiar to the standard Flex background, then here you go:

var mat:Matrix = new Matrix();
var bg:Sprite = new Sprite();
mat.createGradientBox( stage.stageWidth, stage.stageHeight, Math.PI * .5 );
bg.graphics.beginGradientFill( GradientType.LINEAR, [ 0xFFFFFF, 0x000000 ], [ 1, 1 ], [ 0, 255 ], mat );
bg.graphics.drawRect( 0, 0, stage.stageWidth, stage.stageHeight );
bg.graphics.endFill();
addChild( bg );

22 May

Hello and welcome


I lost my last blog to the wonderful server crash of 08 and now I’ve decided to start back up again with added goodness for all the family.

This is mainly a place for my Actionscript experiments and code snippets…


No Response Filed under: talk
Page 5 of 512345