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

use*_*748 9 java android imageview

这是java代码.我从图库中获取图像.我有一个Button和一个ImageView.它只旋转一次.当我再次点击按钮时,它不是旋转图像.

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);


        }
    });



}
Run Code Online (Sandbox Code Playgroud)

Rav*_*yal 32

将您的onClick()方法更改为

@Override
public void onClick(View v)
{                  
    imageView.setRotation(imageView.getRotation() + 90);
}
Run Code Online (Sandbox Code Playgroud)

请注意,文档说的是什么

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


我想更新我的答案,以展示如何使用RotateAnimation以达到相同的效果,以防您同时定位运行Gingerbread(v10)或更低版本的Android设备.

private int mCurrRotation = 0; // takes the place of getRotation()
Run Code Online (Sandbox Code Playgroud)

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

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);
Run Code Online (Sandbox Code Playgroud)

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