0

I have a image with a few buttons on the view. One of the buttons moves the image down. It moves the image down by adding 1 px to the top margin. Here is the code:

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button button = (Button) findViewById(R.id.button1);
        final ImageView image = (ImageView) findViewById(R.id.image1);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ((ViewGroup.MarginLayoutParams) image.getLayoutParams()).topMargin += 1;
                image.requestLayout();
            }
        });
    }

Now, i want to be able to rotate the image. Just like the code i have now, I want a button, when the button is pressed the image will rotate. But how can i do this?

asdf
  • 11
  • 1
  • 1
    you can do this by adding a rotation animation on that button and start that animation when you want it to raotate – Zubair Akber Nov 10 '15 at 05:12
  • Check this out: http://stackoverflow.com/questions/3045832/how-can-i-use-rotateanimation-to-rotate-a-circle/14297097#14297097 – Anoop Kanyan Nov 10 '15 at 05:12

2 Answers2

2
 Bitmap source; //Declare Global
 float angle=0; //Declare Global


Button button = (Button) findViewById(R.id.button1);
        final ImageView image = (ImageView) findViewById(R.id.image1);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
          angle+=70;
          Bitmap rotatedImage=rotateImage(your_image_source,angle);
          img.setImageBitmap(rotatedImage);
            }
        });

public static Bitmap rotateImage(Bitmap sourceImage, float angle)
    {
        Matrix matrix = new Matrix();
        matrix.postRotate(angle);
        return Bitmap.createBitmap(sourceImage, 0, 0, sourceImage.getWidth(), sourceImage.getHeight(), matrix, true);
    }

You can check

  1. Image Rotation in ImageView (Android)
  2. When click a button rotate image clockwise in android

Try this ,I hope it will helps you .

Community
  • 1
  • 1
IntelliJ Amiya
  • 74,896
  • 15
  • 165
  • 198
0
  1. Set the ImageView's scaleType to matrix
  2. Create a new Matrix object
  3. When click the rotate button, call matrix object's postScale method
  4. Set the Matrix object to the ImageView by call setImageMatrix method

imageView.setScaleType(ImageView.ScaleType.MATRIX);
Matrix matrix = new Matrix();
matrix.setRotate(degree); //you can also translate, scale
imageView.setImageViewMatrix(matrix);
Tang Ke
  • 1,508
  • 12
  • 12