Titanium Community Questions & Answer Archive

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

How to change background image of window when orientation changes?

What is the best practice?

— asked March 16th 2010 by Peter Lum
  • background
  • image
  • orientation
0 Comments

2 Answers

  • Hey Peter,

    You might already have this working by now, but just in case something like this should work. Just replace backgroundColor with backgroundImage.

    var win = Ti.UI.currentWindow;
    
    var label1 = Titanium.UI.createLabel({
        color:'#999',
        text:'portrait',
        font:{fontSize:20,fontFamily:'Helvetica Neue'},
        textAlign:'center',
        width:'auto'
    });
    
    win.backgroundColor = '#fff';
    win.add(label1);
    
    win.orientationModes = [ 
        Titanium.UI.PORTRAIT, 
        Titanium.UI.UPSIDE_PORTRAIT, 
        Titanium.UI.LANDSCAPE_LEFT, 
        Titanium.UI.LANDSCAPE_RIGHT, 
        Titanium.UI.FACE_UP, 
        Titanium.UI.FACE_DOWN
    ];
    
    function getOrientation(o) {
        switch (o) {
            case Titanium.UI.PORTRAIT: {return 'portrait';}
            case Titanium.UI.UPSIDE_PORTRAIT: {return 'portrait';}
            case Titanium.UI.LANDSCAPE_LEFT: {return 'landscape';}
            case Titanium.UI.LANDSCAPE_RIGHT: {return 'landscape';}
        }
    }
    
    Ti.Gesture.addEventListener('orientationchange',function(e){
        var orientation = getOrientation(e.orientation);
        if (orientation == 'portrait') {
            win.backgroundColor = '#fff';
            label1.text = 'portrait';
        } else {
            win.backgroundColor = '#000';
            label1.text = 'landscape';
        }
    
    });
    
    — answered March 30th 2010 by Dan Giulvezan
    permalink
    1 Comment
    • The code provided by Dan is good, but the switch()'s are missing break; after each 'case:'

      — commented January 28th 2011 by Mark Henderson
  • The posted code will throw compilation errors … can't use curly braces in case statements… Also, the code in the "else" case of the event handler (landscape mode) will execute on every slight movement of the device… the event gets fired a lot.

    — answered May 8th 2010 by Iko Knyphausen
    permalink
    0 Comments
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.