case
ADM Blog
12Apr/090

How To – Center a image on a canvas in flex


This is the solution for the anoying behaivor of the image control into a canvas or hbox or whatever. If the image is set to be scaled to a maximum width and height and maintaining the aspect ration, it won't center itself even if it has the horizontalCenter set to "0". So...here's how it looks (top) and how it suppose to look (bottom)

canvas

Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
 
    <mx :Script>
        < ![CDATA[
 
                // Maximum  width
                private var mxw:Number = 500;
                // Maximum height
               private var mxh:Number = 250;
 
               public function onImageComplete(e:Event):void
               {
                var wthMaxRatio:Number = mxw / mxh;
 
                // no resize needed
                if (e.target.contentWidth <= mxw && e.target.contentHeight <= mxh)
                {
                    e.target.x = (mxw - e.target.contentWidth) / 2;
                    e.target.y = (mxh - e.target.contentHeight) / 2;
                }
                else
                {
                    var wthImgRatio:Number = e.target.contentWidth / e.target.contentHeight;
 
                    if (wthImgRatio > wthMaxRatio)
                    {
                        // will max out the width
                        e.target.width = mxw;
                        var imgHeight:Number = Math.round( (mxw / e.target.contentWidth) * e.target.contentHeight );
                        var newY:Number = Math.round( (mxh - imgHeight) / 2 );
                        e.target.x = 0;
                        e.target.y = newY;
                    }
                    else
                    {
                        // will max out the height
                        e.target.height = mxh;
                        var imgWidth:Number = Math.round( (mxh / e.target.contentHeight) * e.target.contentWidth );
                        var newX:Number = Math.round( (mxw - imgWidth) / 2 );
                        e.target.x = newX;
                        e.target.y = 0;
                    }
                }
              }
         ]]>
    </mx>
 
 
      <mx :Canvas width="500" height="250"
            verticalScrollPolicy="off" horizontalScrollPolicy="off"
            backgroundColor="#000000">
 
            <mx :Image id="theimage"
                maintainAspectRatio="true"
		scaleContent="true"
                complete="onImageComplete(event)" />
 
        </mx>