View Full Version : Centering a dynamic image

05-30-2009, 02:27 PM
I am new to Flex and very new to this forum and naturally I have found a concept in Flex that I just can't seem to get my head around. I can't find any reference to it and as it is pretty basic I must be doing something wrong.

I am designing an AIR product but that make no difference it's the same in an online project too.

I have multiple photo's that are referenced in a datagrid. I have opened another windows window to display the various images in a vBox the elements in the vBox are to be centered on the screen.

When I select an item in the datagrid that photo appears in the window, this is done by changing the source of the image, that part works no worries.

But all of the photo's are different sizes so when I load a tall narrow picture into a slot previously occupied by a short narrow one it is offset to the left and not in the middle as I have asked it to be.

I've tried every thing I can think of even a work around to set the x y coordinates but it will not center.

Any ideas?


05-30-2009, 08:06 PM
This was how I did it, but maybe there is a better way.

override protected function updateDisplayList(unscaledWidth:Number, unscaledHeight:Number):void {

if( (!myMovedOnce) && myImgLoaded ) {
var xOffset:Number;
var yOffset:Number;

var xscale:Number = idImg.measuredWidth/idImg.contentWidth;
var yscale:Number = idImg.measuredHeight/idImg.contentHeight;

//center and scale image if needed
if( xscale == 1 && yscale == 1 ) {
xOffset = (idImgCanvas.width-idImg.measuredWidth)/2;
yOffset = (idImgCanvas.height-idImg.measuredHeight)/2;
idImg.x = xOffset;
idImg.y = yOffset;
else if( xscale > yscale ) {
xOffset = (idImgCanvas.width/2)-(idImg.measuredWidth/2) + (idImg.measuredWidth-idImg.contentWidth*yscale)/2;
yOffset = (idImgCanvas.height/2)-(idImg.measuredHeight/2);
idImg.x = xOffset;
idImg.y = yOffset;
else {
xOffset = (idImgCanvas.width/2)-(idImg.measuredWidth/2);
yOffset = (idImgCanvas.height/2)-(idImg.measuredHeight/2) + (idImg.measuredHeight-idImg.contentHeight*xscale)/2;
idImg.x = xOffset;
idImg.y = yOffset;

myMovedOnce = true;

super.updateDisplayList( unscaledWidth, unscaledHeight );

This function is listed in a pop up window with an Image (idImg) inside of a Canvas (idImgCanvas). You will need to adapt the concept to fit your purposes.

Best Regards,

05-31-2009, 03:58 PM
Thanks for that I'll give it a go. There is something there that I have not tried so fingers crossed.

Thanks again