Stroep

Just a collection of random works – Mark Knol

Tag Archives: as3

ChainI created a useful util-class to make delayed function calling easy. You can make a chain of functions, by adding them with a delay in milliseconds. This chain can be executed multiple times, even in reversed order.

Let’s take a look at a simple example of Chain.

var myChain:Chain = new Chain();   
myChain.addEventListener( Event.COMPLETE, onComplete);
myChain.add(one, 2000).add(two, 500).add(three, 1000).play(2);

function one():void { trace("one") }
function two():void { trace("two") }
function three():void { trace("three") }
function onComplete(e:Event):void { trace("done.") }

/* trace output:
one two three one two three done.
*/

 

What is happening here? At the first line we are instantiating the class, and the second line represents what chain does. There is a public function called ‘add’, which is an important part of the class. add(one, 2000) means: execute a function called ‘one’ after 2000 milliseconds. add(two,500).add(three,1000) are functions that are called after one is finished, with other delays. You can create your own rhythm/sequence/pattern. At the end we see play(2), which means: Execute the sequence of functions defined before, and repeat them 2 times. After that, dispatch event COMPLETE.

So that’s basically it. A cool part is you can play it reversed, using playReversed(). I am inspired by jQuery (which has nothing to do with this) to enable the ability to stick functions, but thats optional.

myChain.playReversed(2);

/* trace output:
three two one three two one
*/

 

Of course you can pauze/continue when you are playing, by calling stop() / doContinue(), and you can determine if it is currently playing using the isPlaying-getter.

These are all the public functions.

/// Constructor
public function Chain()

/// Adds a function at a specified interval (in milliseconds).
public function add(func:Function, delay:Number = 0):Chain

/// Start playing the sequence and calling functions
public function play(repeatCount:int = 0):void

/// Start playing the sequence reversed
public function playReversed(repeatCount:int = 0):void

/// Clears sequence list. Data will be removed.
public function clear():Chain

/// Stop playing, use doContinue to play futher from current point
public function stop():void

/// Continue playing after a stop
public function doContinue():Chain

/// Reset indexes
public function reset():void

/// Returns the string representation of the Chain private vars.
public function toString():String

/// Return chain is playing, stopped or completed
public function get isPlaying():Boolean
 

Hope you like it, let me know if you like to see extra/other related features.

Download: Chain (googlecode)

Updates
- Private functions are protected
- add-functions is now add(function, delay), where function is required.
- Class now extends EventDispatcher and play/playReversed dispatches Event.COMPLETE after playing sequence, instead of calling onComplete function
- Cleaned up code

Tagged with , , , .

I’ve updated my Image class. It is irritating flashsites break the right-click contextmenu. Well, I can’t fix that and Adobe should look at that, but I think it would nice to add some of the browser – features to my image class.

Currently I have these options added to the Image class:

View image
Views image in new window/tab. I used NavigateToURL to make this happen.

Save Image as..
Saves image on your computer. I used my ImageClass.saveLocal() to make this happen. This is only available within FP10, but I think this is no problem anymore because < a href = "http://www.adobe.com/products/player_census/flashplayer/version_penetration.html" > 93 % (September 2009) has FlashPlayer 10, so most people have it, and I don’t support outdated software ;)

Copy Image location
Copies the url to the clipboard, using System.setClipboard(url). It’s a pity I can’t create a ‘Copy Image’ function, because pushing bitmapdata into the clipboard is only supported in AIR.

Send Image
Sends the url to the mail-client, using “mailto:&body=” + src. Also a pity; I can’t add the image directly into the mail.

How to enable the contextmenu:

import nl.stroep.utils.Image;

var myImage:Image = new Image("myImage.jpg");
myImage.enableContextMenu = true; // enable it!
this.addChild(myImage);
 

I still love this class, I use it a lot. I want to encourage you to please add these kind of usability things to your apps / websites. And share them! Yes, it takes some extra time to create/add it, because this IS the finishing touch, but a lot of people will like this kind of features.

Download
Check out the Image class atgooglecode

Tagged with , , , .

Square rootFound out something useful, which I’d like to share with you. It’s about calculating the width of menu-items perfectly.

Imaging you are creating a liquid website with a menu. If you want all items to have the same width, you could set the width of each item to totalMenuWidth / items.length. In most cases this will work out. But what is your menu is very small or the items doesn’t fit in that fixed width because the text is too long?

Well you could hardcode the width’s to make your own perfect proportions and spacing, but if your menu is xml-driven and you/someone else adds new menu-items, you have to re-assign the hardcoded widths and you feel unhappy :) Most hardcoded stuff is evil anyway because it is laziness. (I use it a lot :P )

Well, I’d like to calculate the perfect scaling menu, so I don’t have to worry the menu will break. You can use the text-length of the menu-item as input for the width calculation. The more letters, the bigger the menu-item, right? So, If you multiply all menu-text-lengths and divide this to the current text-length, you’ll get a ratio which can be divided from the total menu width. I like this theory. So we need to do this in 2 steps; first get the ratios and get the total menu-text-lengths (with a loop), then calculate and apply this on each item.
Pseudocode:

itemwidth = fullMenuWidth / (totalTextLength / menuitem.text.length)

This works fine, and its actually very cool. Now we have a function which actually use some proportions to create a liquid menu. After a while I realized that the proportions weren’t really right. If the menu text have odd text-length differences (eg 5 letters vs 25 letters), it looks weird. Larger texts take too much width. I wanted the same proportions kinda like a html-table.

So the menu-items needs to have better proportions. Bigger text should be a smaller and the smaller text should be bigger. After some searching I ‘discovered’ Square root, a.k.a. Math.sqrt() in actionscript. With this function you could ‘normalize’ numbers. Bigger numbers are getting smaller, smaller numbers are getting bigger. This was exactly what I needed!

You can see the result below:

[kml_flashembed publishmethod="static" fversion="9.0.0" movie="http://projects.stroep.nl/PerfectWidth/PerfectWidth.swf" width="100%" height="235" targetclass="flashmovie" wmode="transparent"]

Get Adobe Flash player

[/kml_flashembed]

You can see the differences between the menubars and you’ll agree to me that the last one is the best :) I think this theory could be applied to a lot more things, like graphs or grids.

In case anyone is interested in the code; it can be downloaded here (AS3).

Tagged with , , .

Code snippetEasily create an image without taking care of loaders and URLRequest etc.
Most simple usage of the Image class:

import nl.stroep.utils.Image

var myImage:Image = new Image("myImage.jpg");
this.addChild(myImage)
 

You can also add the most common eventListeners to the image:

import nl.stroep.utils.Image

var myImage:Image = new Image("myImage.jpg");
this.addChild(myImage);

myImage.addEventListener(Event.COMPLETE, onImageLoaded );
myImage.addEventListener(IOErrorEvent.IO_ERROR, onImageError );
myImage.addEventListener(ProgressEvent.PROGRESS, onImageLoading );

function onImageLoaded (e:Event):void {
   trace("image loaded!");
}

function onImageError (e:IOErrorEvent):void {
   trace("image error", e.text);
}

function onImageLoading (e :P rogressEvent):void {
   trace("loading image.. bytesLoaded=" + e.bytesLoaded + " bytesTotal=" + e.bytesTotal );
}
 

Download
Check out the Image class at googlecode

Tagged with , , , .

Quick post; How to crop the bitmap of your stage with AS3:

function crop( _x:Number, _y:Number, _width:Number, _height:Number, displayObject:DisplayObject = null):Bitmap
{
var cropArea:Rectangle = new Rectangle( 0, 0, _width, _height );
var croppedBitmap:Bitmap = new Bitmap( new BitmapData( _width, _height ), PixelSnapping.ALWAYS, true );
croppedBitmap.bitmapData.draw( (displayObject!=null) ? displayObject : stage, new Matrix(1, 0, 0, 1, -_x, -_y) , null, null, cropArea, true );
return croppedBitmap;
}
 

Usage:

var myCroppedImage:Bitmap = crop( 100, 100, 200, 200 );
this.addChild ( myCroppedImage );
 

To save the capture, use the ImageSaver class

Update: I’ve added a downloadable CropUtil class to googlecode.

Tagged with , .

Since I am using actionscript 3 and an external actionscript editor with nice code completion (FlashDevelop in my case), I am using a lot of value objects.

Flashdevelop has no value object generator tool, so I’ve build one myself. It is beta.

ValueObject generator
http://projects.stroep.nl/ValueObjectGenerator/


Tagged with , , , , , , , .

AS3 ImageSaver Class updated (9)

September 10th, 2008, under Actionscript.

The ImageSaver Class is updated.

Download
ยป ImageSaver (latest)

Fixed:
- You can use a bitmapdata as input too. First you only could use a displayObject, but I believe it’s better to use an IBitmapDrawable (interface).
- Bug quality JPG
- Added optional rect

Tagged with , , .