Sunday, August 20, 2017

Rotate android layout view about its center using touch listener

Leave a Comment

Here is how my set up to rotate looks.

enter image description here

I am listening for action down and move on the rotation icon, trying to calculate the angle of rotation and applying that angle of rotation to entire layout encapsulating the edittext. The applied rotation has to be about the center of encapsulating relative layout.

Here is how I am trying to achieve this, in the touchListener for rotation icon.

if(v == ivRotateSticker){           //TODO grab xc and yc using (top and bottom)/2 and (left and right)/2 to grab center of sticker after each rotation         final float x = event.getX();         final float y = event.getY();         rlTextStickerLayout.getGlobalVisibleRect(myViewRect);         xc = myViewRect.width()/2;         yc = myViewRect.height()/2;          dx = scaleReceiver.getWidth() - myViewRect.width();         dy = scaleReceiver.getHeight() - myViewRect.height();          leftBound = scaleReceiver.getX();         topBound = scaleReceiver.getY();          switch (event.getAction()){              case MotionEvent.ACTION_DOWN:                 mViewAngle = rlTextStickerLayout.getRotation();                 mPrevAngle = Math.toDegrees(Math.atan2(x - xc, yc - y));                  break;              case MotionEvent.ACTION_MOVE:                  Log.d("EventRegistered", " " + event.getRawX() + "--" + dx + " -- " + dy);                  mCurrAngle = Math.toDegrees(Math.atan2(x - xc, yc - y));                 if (x >= leftBound && y >= topBound && x <= dx && y <= dy) {                     float rot = (float) (mViewAngle + mCurrAngle - mPrevAngle);                     rlTextStickerLayout.setRotation((float) (mViewAngle + mCurrAngle - mPrevAngle));                     Log.d("stickerRotation"," "+rot);                 }                 break;          }          return true;      } 

But the resulting rotation is glitchy and not as desired smooth. Also, if I move the sticker to a different location, how do I update the new center for rotation, as rotation after moving the sticker dramatically changes the center of rotation. How can I achieve a far more smooth rotation?

2 Answers

Answers 1

  1. View's rotation to be animated to the specified values (90, 180, 270) in 1000ms:

    view.animate().rotation(90f).setDuration(1000).start(); view.animate().rotation(180f).setDuration(1000).start(); view.animate().rotation(270f).setDuration(1000).start();

  2. Using this library you can rotate whole view hierarchy https://github.com/rongi/rotate-layout

Answers 2

I think this library will help you a lot.

https://github.com/kencheung4/android-StickerView

its smooth and easy.

If You Enjoyed This, Take 5 Seconds To Share It

0 comments:

Post a Comment