Search code examples
imagerotationtitaniumcenter

Set center of rotation [Titanium]


I have got some code for rotation of an image. But however, the center of rotation is not equal to the center of the image which is to be rotated.

I have set the center of an image but I don't know how to set the center of the rotation.

Following is the code :

 // image code
var image = Titanium.UI.createImageView({
    backgroundImage:'test.png',
    width: 650,
    height: 650,
    center:{x:CenterX, y:CenterY},
    align:'center'
});
//rotation code
image.addEventListener('touchstart', function(e){
    var conv = e.source.convertPointToView({x: e.x, y:e.y}, win);

    var newAngle = Math.atan2(conv.y - 500, 380 - conv.x)* -(180 / Math.PI);  
    diff = (newAngle - old);

});

image.addEventListener('touchmove', function(e){

      var conv = e.source.convertPointToView({x: e.x, y:e.y}, win);

      var newAngle = Math.atan2(conv.y - 500, 380 - conv.x)* -(180 / Math.PI);
      current = (newAngle-diff); 
      var t = Ti.UI.create2DMatrix().rotate(current);
      wheel.transform = t;

});

Solution

  • You have to set the animation / view anchorPoint, on iOS you have to set the Ti.UI.View's anchorPoint, on Android you have to set the Ti.UI.Animation's anchorPoint or in your case, since your using a Matrix, just set the anchorPoint of the Matrix on creation (for Android).

    Here is what you do for iOS:

    /* iOS */
    var image = Titanium.UI.createImageView({
        backgroundImage:'test.png',
        width: 650,
        height: 650,
        anchorPoint: {0.5, 0.5}, // ANchor point is at the center
    });
    

    Or alternatively, on Android:

    /* Android */
    // Matrix, inside your event listener
    image.addEventListener('touchmove', function(e){
    
        var conv = e.source.convertPointToView({x: e.x, y:e.y}, win);
    
        var newAngle = Math.atan2(conv.y - 500, 380 - conv.x)* -(180 / Math.PI);
        current = (newAngle-diff); 
    
        // Note that I set the anchor point here.
        var t = Ti.UI.create2DMatrix({anchorPoint: {0.5, 0.5}}).rotate(current);
        wheel.transform = t;
    });