mattlundstrom
12/16/2013 - 12:10 AM

fill fit and center one display object to another

fill fit and center one display object to another

function centerTo(_object:DisplayObject, _ref:DisplayObject):void{
	if (_object != null){
		var _wString:String  = "width";
		var _hString:String  = "height";
		if (_ref == stage){
			_wString = "stageWidth";
			_hString = "stageHeight";
			trace("stage");
		}
		var _refWidth:Number = _ref[_wString];
		var _refHeight:Number = _ref[_hString];
		
		_object.x = (_refWidth - _object.width) / 2;
		_object.y = (_refHeight - _object.height) / 2;
	}

}

function fitTo(_object:DisplayObject, _ref:DisplayObject):void{
	if (_object != null){
		var _wString:String  = "width";
		var _hString:String  = "height";
		if (_ref == stage){
			_wString = "stageWidth";
			_hString = "stageHeight";
		}
		var _refWidth:Number = _ref[_wString];
		var _refHeight:Number = _ref[_hString];
		var _objectRatio:Number = _object.width / _object.height;
		var _refRatio:Number = _refWidth / _refHeight;
		
		if (_refRatio>=_objectRatio){
			_object.x = 0;
			_object.width = _refWidth;
			_object.height = _object.width / _objectRatio;
			_object.y = (_refHeight - _object.height) / 2;
		}
		else 
		{
			_object.y = 0;
			_object.height = _refHeight;
			_object.width = _object.height * _objectRatio;
			_object.x = (_refWidth - _objectRatio.width) / 2;
		}
	}
}

function fillTo(_fitDo:DisplayObject, _referenceDo:DisplayObject):void{
	if (_object != null){
		var _wString:String  = "width";
		var _hString:String  = "height";
		if (_ref == stage){
			_wString = "stageWidth";
			_hString = "stageHeight";
		}
		var _refWidth:Number = _ref[_wString];
		var _refHeight:Number = _ref[_hString];
		
		_object.x = (_refWidth - _object.width) / 2;
		_object.y = (_refHeight - _object.height) / 2;
		_object.width = _refWidth;
		_object.height = _refHeight;
	}
}