So I have a load an image from a httpclient,
and after doing so I try and process it like this:
xhr.onload = function() { imageFoto.image = this.responseData; imageFoto.width = 300; };ImageFoto is an empty imageView I created, and the image is displayed in the imageView. However, the scaling isn't correct. Whether I change the width from 300 to 200 or anything else, the height of the image remains the same. How do I get it to scale according to the aspect ratio of the image?
1 Answer
I had to solve this by changing my web service to retrieve an image URL along with height and width properties. Then I compute the aspect ratio in my Titanium code, setting the height and width accordingly.
I've seen some techniques for getting the height and width of an image by loading the image into another ImageView. Some of the examples I've read suggest you can do this without even adding the "dummy" ImageView into a view. But I don't think that works with the current SDK.
I played around with this a bit, and here's some sample code that can get the height and width:
var win = Ti.UI.createWindow({ backgroundColor: '#fff' }); var iv = Ti.UI.createImageView ({ image: '/images/foo.jpg', height: Ti.UI.SIZE, width: Ti.UI.SIZE, visible: false }); var ivpostlayout = function (e) { iv.removeEventListener ('postlayout', ivpostlayout); var w = iv.size.width; var h = iv.size.height; alert ('w, h: ' + w + ", " + h); } iv.addEventListener ('postlayout', ivpostlayout); win.add (iv); win.open();With a little creativity, you could turn this into a nifty little CommonJS module that could take an image filename/url, and fire an event that gives you the height/width.
There are some challenges here, though:
this is all asynchronous, so you'll have to add the dummy ImageView to an open view and wait for the size before you can put your "real" ImageView into the window
this is not particularly efficient, since the image is going to be decoded twice
If you can get the server to send you this information, it will be more efficient. Hell, it would probably be more efficient to parse the PNG in javascript if all you're trying to get is the height and width
Your Answer
Think you can help? Login to answer this question!