如何在每次点击按钮时在图像视图中旋转图像?

2022-09-04 05:44:18

这是java代码。我从图像库获取图像。我有一个按钮和一个图像视图。它只旋转一次。当我再次单击按钮时,它不会旋转图像。

public class EditActivity extends ActionBarActivity
{
private Button rotate;
private ImageView imageView;
@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_edit);
    rotate=(Button)findViewById(R.id.btn_rotate1);
    imageView = (ImageView) findViewById(R.id.selectedImage);
    String path = getIntent().getExtras().getString("path");
    final Bitmap bitmap = BitmapFactory.decodeFile(path);
    imageView.setScaleType(ImageView.ScaleType.FIT_XY);
    imageView.setImageBitmap(Bitmap.createScaledBitmap(bitmap, 510, 500,
            false));
    rotate.setOnClickListener(new View.OnClickListener()
    {
        @Override
        public void onClick(View v)
          {                  
            imageView.setRotation(90);


        }
    });



}

答案 1

将方法更改为onClick()

@Override
public void onClick(View v)
{                  
    imageView.setRotation(imageView.getRotation() + 90);
}

注意,文档说什么

设置视图围绕枢轴点旋转的度数。值的增加会导致顺时针旋转。


我想更新我的答案,以显示如何使用来实现相同的效果,以防您还针对运行姜饼(v10)或更低版本的Android设备。RotateAnimation

private int mCurrRotation = 0; // takes the place of getRotation()

引入一个实例字段来跟踪上述旋转度,并将其用作:

mCurrRotation %= 360;
float fromRotation = mCurrRotation;
float toRotation = mCurrRotation += 90;

final RotateAnimation rotateAnim = new RotateAnimation(
        fromRotation, toRotation, imageview.getWidth()/2, imageView.getHeight()/2);

rotateAnim.setDuration(1000); // Use 0 ms to rotate instantly 
rotateAnim.setFillAfter(true); // Must be true or the animation will reset

imageView.startAnimation(rotateAnim);

通常也可以通过XML设置这样的视图动画。但是,由于您必须在其中指定绝对度值,因此连续的旋转将重复自己,而不是在前一个旋转的基础上完成一个完整的圆。因此,我选择在上面的代码中展示如何做到这一点。


答案 2

推荐