Tutorials, extensions, and source files for ActionScript, Flash, and other Adobe products.

 

senocular.com ActionScript Library

attachAndCenter.as

Name: attachAndCenter() - attaches, then scales and centers a linked clip into 'this' clip
Author: senocular: www.senocular.com
Date: 1899-12-31T00:06:47.600
Documentation:
Movieclip ATTACHANDCENTER: attaches a movieclip from the
library specified by the linker argument into this clip, then it
scales the clip to fit (adding padding where appropriate but
maintaining scale ratio) and centers within the bounds of this.
 
Arguments:
- linker: Linker ID of clip to attach as specified in Library linkage
- name: The new instance name of the clip to be attached
- depth: The depth of which the attached clip is to be placed
- pad: (optional) the "padding" around the this clip which would be obtained as a
result of scaling the attached clip down from being the same size.  This value can be
positive (scaled down) or negative (scaled up).  Default is 0.
 
Returns:
- returns a reference to the attached clip.
 
Application:
- Ive used this in dynamically creating menus where I attached graphics (movieclips),
who originally all have different sizes and varying reg points, in generic square or
rectangular button clips centered cleanly keeping proportion.
 
Example:
// When this clip loads, it attaches and scales the clip linked with
// "ball" in the library to the center of itself scaled to its own
// size minus the padding of 5
onClipEvent(load){
	this.attachAndCenter("ball", "ball_mc", 1, 5);
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
MovieClip.prototype.attachAndCenter = function(linker, name, depth, pad){
	var tb = this.getBounds();		// This Bounds
	var tw = this._width - pad*2;	// This Width
	var th = this._height - pad*2;	// This Height
	this.attachMovie(linker, name, depth);
	var a = this[name];		// Attached clip
	var hr = th/a._height;		// Height Ratio
	var wr = tw/a._width;		// Width Ratio	
	a._xscale = a._yscale *= Math.min(hr, wr);
	ab = a.getBounds(this);		// Attached clip Bounds
	a._x = tb.xmin + pad - ab.xmin + (tw - a._width)/2;
	a._y = tb.ymin + pad - ab.ymin  + (th - a._height)/2;
	return a;
}