astralmaster
astralmaster

Reputation: 2465

Scale object in as3

I have this function that I found on the net for scaling objects and keeping them in their original positions:

function scaleAroundPoint(target:DisplayObject, point:Point, scaleFactor:Number):void 
{ 
      var m:Matrix = target.transform.matrix; 
      m.translate( -point.x, -point.y ); 
      m.scale( scaleFactor, scaleFactor); 
      m.translate( point.x, point.y ); 
      target.transform.matrix = m; 

}

When I call it at first like this:

 scaleArountPoint(obj, p, 0.9);

The object DOES scale down, but then, when I want to return it back to its original size, obviously this doesnt work:

scaleArountPoint(obj, p, 1);

Because 1 is the current scale ratio of the object.

So how would I scale it back to its original proportions? thanks

Upvotes: 1

Views: 1582

Answers (2)

Neil
Neil

Reputation: 8111

One way you could do this is by storing the original matrix of the target and always applying the scaleFactor to this.

The only problem is that this is only going to work for one object as the orig will be stored when one call has been made to this function.

If you want to use this function with any number of objects then it needs a little more thought, but it should be enough for you to start with.

import flash.display.Sprite;
import flash.geom.Point;
import flash.geom.Matrix;

var currentScaleFactor:int = 1;
var orig:Matrix;

function scaleAroundPoint(target:DisplayObject, point:Point, scaleFactor:Number):void 
{ 
  if(orig == null)
    orig = target.transform.matrix;

  var m:Matrix = orig.clone();
      m.translate( -point.x, -point.y ); 
      m.scale( scaleFactor, scaleFactor); 
      m.translate( point.x, point.y ); 
      target.transform.matrix = m; 
}

var spr:Sprite = new Sprite();
spr.graphics.beginFill(0x660000);
spr.graphics.drawCircle(100,100,100);
spr.graphics.endFill();

addChild(spr);

// set identity scale
scaleAroundPoint(spr, new Point(50,50), 1);

// try an arbitrary scale
scaleAroundPoint(spr, new Point(50,50), 0.2);

// revert to original scale
scaleAroundPoint(spr, new Point(50,50), 1);

Upvotes: 2

pho
pho

Reputation: 25489

Save the changed scale. So when you do scaleAroundPoint(obj, p, 0.9), save that 0.9 somewhere.

Then when you want to scale to original dimensions, scale to 1 / currentScale

Note that when you call scaleAroundPoint multiple times (for the same object), you'll need to multiply the new scale with the current scale, (currentScale *= scaleFactor), so if you scale twice by 50%, it will understand that the new scale is 25% of the original scale.

Upvotes: 0

Related Questions