Titanium Community Questions & Answer Archive

We felt that 6+ years of knowledge should not die so this is the Titanium Community Questions & Answer Archive

Scaling an ImageView and maintaining aspect ratio

Hey all,

As suggested in the title what I'm trying to do is take an image from the web that I know will be 200px wide but variable height, position it in the top left corner of my view, resize it to x pixels wide with the height being scaled whatever it needs to be to keep aspect ratio.

The docs for createImageView say 'if you specify a width and/or height property on the image, the image will be scaled to fit into this space if the image is larger', which suggests that you don't need to specify both, but if I do that the background image appears as usual while the image is usually loading, then a second later nothing is there.

I've tried various other things suggested in similar other questions such as specifying the image as the backgroundImage, trying to modify the image on the load event (reading the image width from event.source.toImage().width and calculating) and adding the ImageView to a View and scaling that.

All of those gave me some success but mostly appeared to be cropping without scaling at all, not to mention doing strange things with positioning.

Any ideas?



— asked June 4th 2010 by Jon Gilbraith
  • createimageview
  • imageview
  • iphone
  • mobile
  • scaling

2 Answers

  • Accepted Answer

    Hi Jon,

    Prob not strictly a bug, more like a limitation in the standard (out-of-the-box) approach.

    The properties are determined when the view is created, if the image is remote, then the app won't have the image yet - so can't workout it's dimensions.

    I suggest using the 'load' event for the imageView and re-setting the height and width in that listener. Haven't checked myself but the theory sounds plausible.


    — answered June 5th 2010 by Chris Reed
  • Hi Jon,

    Setting ({… width:200, height:'auto' …}); seems to do what you need.


    — answered June 5th 2010 by Chris Reed
    • Hey Chris, thanks for responding. That was one of the things I tried, but had no joy. Maybe I'm overlooking something else simple.

      Here's a sample of my code:

      var image = Ti.UI.createImageView({
        url:    'http://graph.facebook.com/651971287/picture?type=large',
        top:    10,
        left:   10,
        height: 'auto',
        width:  200

      Look ok?

      — commented June 5th 2010 by Jon Gilbraith
    • Seems this is something to do with using a remote image - if I point it to something local it works as expected.

      A bug maybe?

      — commented June 5th 2010 by Jon Gilbraith
    • Ugh, this was a problem 3 years ago, and still plagues me today

      — commented April 8th 2013 by Eric Wooley
The ownership of individual contributions to this community generated content is retained by the authors of their contributions.
All trademarks remain the property of the respective owner.