Thursday, December 22, 2011

Titanium Image Gallery

Creating an Image Gallery that scrolls side to side isn't terribly difficult with Titanium.

Here is how I did it:

// put this in a file, for instance "ImageGallery.js"
var ImageGallery = {};
(function() {

    ImageGallery.imageViewArray = [];
    ImageGallery.imageNameArray = [];
    ImageGallery.nextImageIndex;
    ImageGallery.Gallery = null;
   
   
    ImageGallery.createGallery = function(params) {
       
        if (params.Images) {
            ImageGallery.imageNameArray = params.Images;
        }
        ImageGallery.init(params);
       
        ImageGallery.Gallery.addEventListener('click', function(e){});
        for(var i = 0; i < ImageGallery.imageNameArray.length ; i++){
            ImageGallery.Gallery.views[i].image = ImageGallery.imageNameArray[i];
        }
        ImageGallery.nextImageIndex = 1;
       
        return ImageGallery.Gallery;
    };
   
    ImageGallery.init = function(params) {
        var imageParams = {
            width:Ti.Platform.displayCaps.platformWidth - 4,
            height:Ti.Platform.displayCaps.platformHeight/2,
            hires:true,
            left:2,
            right:2
        };
       
        for(var i = 0; i < ImageGallery.imageNameArray.length ; i++){
            ImageGallery.imageViewArray[i] = Titanium.UI.createImageView(imageParams);
        }
       
        var p = {
            width: 310,
            height: 450,
            top: 5,
            left: 5,
            borderWidth: 2,
            borderColor: '#000',
            showPagingControl: false,
            pagingControlColor: '#fff',
            currentpage:0
        };
        for (var prop in params) {
            p[prop] = params[prop];
        }
        p.views = ImageGallery.imageViewArray;
        p.backgroundColor = "#000";
        ImageGallery.Gallery = Titanium.UI.createScrollableView(p);
    };
   
})();


 Assuming that you include the file above in your view, you then can use it like so:

var gallery = ImageGallery.createGallery(
            {

                // here images is an array of image URLs
                Images:images,
                width:Ti.Platform.displayCaps.platformWidth,
                height:Ti.Platform.displayCaps.platformHeight/2,
                top:null,left:null
            }
        );


What do you think?

3 comments:

c4ux said...

how is the image array supposed to look?
don't get it to work. thank u

Ed said...

Images is an array of Image URLs. So construct an array with your urls in it and pass it into the function like the example shows.

Cristy said...

Really helpful.