I am trying to rotate image single round from it’s center point but I am not able to stop at desire position as I can do rotation but I want to stop rotation after 360'(1 round).
public class RotateRoundActivity extends Activity implements OnTouchListener
{
private ImageView dialer;
//private float y=0;
private float x=0;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
dialer = (ImageView) findViewById(R.id.big_button);
dialer.setOnTouchListener(this);
}
@Override
public boolean onTouch(View v, MotionEvent event) {
// double r=Math.atan2(event.getX()-dialer.getWidth()/2, dialer.getHeight()/2-event.getY());
double r=Math.atan2(event.getX()-dialer.getWidth()/2, dialer.getHeight()/2-event.getY());
int rotation=(int)Math.toDegrees(r);
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
break;
case MotionEvent.ACTION_MOVE:
x=event.getX();
// y=event.getY();
updateRotation(rotation);
break;
case MotionEvent.ACTION_UP:
break;
}//switch
return true;
}
Rotation method@
private void updateRotation(double rot){
float newRot=new Float(rot);
Bitmap bitmap=BitmapFactory.decodeResource(getResources(),R.drawable.ic_launcher);
Matrix matrix=new Matrix();
matrix.postRotate(newRot,bitmap.getWidth(),bitmap.getHeight());
Log.i("demo===>", "matrix==>" + matrix);
// Log.i("demo===", "y===>" + y);
Log.i("demo===", "x===>" + x);
if(x>250){
Bitmap reDrawnBitmap=Bitmap.createBitmap(bitmap,0,0,bitmap.getWidth(),bitmap.getHeight(),matrix,true);
dialer.setImageBitmap(reDrawnBitmap);
}
else{
Bitmap reDrawnBitmap=Bitmap.createBitmap(bitmap,0,0,bitmap.getWidth(),bitmap.getHeight(),matrix,true);
dialer.setImageBitmap(reDrawnBitmap);
}
}
}
Your suggestions are appreciable.
You have to save previous
rotvalue. And add check inupdateRotationmethod ifpreviousRotis at the left of 360′ degrees androtis at the right of 360′ degrees then we made 1 round and need stop rotating.Sample code for clockwise case
For counter clockwise case it is almost the same, but the values swapped
This code will stop rotation. From the beginning
previousRotshould be 0 for clockwise case and 359.99 for counter clockwiseAnother approach is to add one more variable to store total traveled angle. From the beginning
traveledAnglehave to be equal to 0. And if you’re rotating in clockwise direction you have to increase it by the difference betweenrotandpreviousRot. When rotating counter clockwise decrease it by the same value.When
traveledAnglebecomes greater than 360′ you need to stop rotating in clockwise direction, and when it becomes less than 0, you need to stop rotating in counter clockwise direction.