简体   繁体   English

使用按钮在Android中旋转图像

[英]Rotating image in Android with a button

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. 通过在顶部边缘增加1 px,图像向下移动。 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? 但是我该怎么办呢?

 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) ImageView中的图像旋转(Android)
  2. When click a button rotate image clockwise in android 当单击按钮时在Android中顺时针旋转图像

Try this ,I hope it will helps you . 试试这个,希望对您有帮助。

  1. Set the ImageView's scaleType to matrix 将ImageView的scaleType设置为matrix
  2. Create a new Matrix object 创建一个新的Matrix对象
  3. When click the rotate button, call matrix object's postScale method 单击旋转按钮时,调用矩阵对象的postScale方法
  4. Set the Matrix object to the ImageView by call setImageMatrix method 通过调用setImageMatrix方法将Matrix对象设置为ImageView

imageView.setScaleType(ImageView.ScaleType.MATRIX);
Matrix matrix = new Matrix();
matrix.setRotate(degree); //you can also translate, scale
imageView.setImageViewMatrix(matrix);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM