I have an oversized image that I want to move up, down, left and right, using the Accelerometer values. I have created the following code that works, but the image moves in distinct steps and does not slide smoothly.
float[] matrix = new float[9];
mMatrix.getValues(matrix);
if (accelerometerValues[0] < MOVE_RIGHT_LIMIT) {
mMatrix.setTranslate(matrix[2] + 10, matrix[5] );
mSchematicDiagram.setImageMatrix(mMatrix);
Log.d("PROJECTA_SENSOR", "Moving Right");
Is it correct to use the setTranslate on ImageView matrix for this sort of use case and how would you create this smooth transition ?
i'm not sure what kind of image you want to move and why using matrix, but if you have an ImageView, you can do it by setting X and Y values in onSensorChanged method
@Override
public void onSensorChanged(SensorEvent event) {
if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
x -= (int) event.values[0];
y += (int) event.values[1];
yourImageView.setY(y);
yourImageView.setX(x);
}
}
Here is my MainActivity code that works well (I just need to add borders, because currently the image can move out of the screen borders), probably it will help somebody.
import android.app.Activity;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.widget.ImageView;
public class MainActivity extends Activity implements SensorEventListener{
private SensorManager sensorManager;
private Sensor accelerometer;
private long lastUpdate;
ImageView mDrawable;
public static int x = 0;
public static int y = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mDrawable = (ImageView) findViewById(R.id.image);
sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
accelerometer = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
lastUpdate = System.currentTimeMillis();
}
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(this, accelerometer,
SensorManager.SENSOR_DELAY_GAME);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(this);
}
@Override
public void onSensorChanged(SensorEvent event) {
if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
x -= (int) event.values[0];
y += (int) event.values[1];
mDrawable.setY(y);
mDrawable.setX(x);
}
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With