【问题标题】:How to rotate image in imageview on button click each time?如何在每次单击按钮时在 imageview 中旋转图像?
【发布时间】:2015-03-31 07:47:11
【问题描述】:

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


        }
    });



}

【问题讨论】:

  • 我想提请注意,这个问题需要连续旋转,然后完成一个完整的循环。另一方面,建议的副本将旋转一个象限并一遍又一遍地重复相同的内容。

标签: java android imageview


【解决方案1】:

将您的 onClick() 方法更改为

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

注意,docs 说什么

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


如果您还针对运行 Gingerbread (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 设置View animations。但是,由于您必须在其中指定绝对度数,因此连续的旋转将自行重复,而不是在前一个旋转的基础上完成一个完整的循环。因此,我选择在上面的代码中展示如何做到这一点。

【讨论】:

  • 很高兴为您提供帮助。尽可能不要忘记投票/接受答案:)
  • @Darpan 感谢您的反馈。我添加了一个更新来展示如何在 Gingerbread 或以下版本上支持旋转动画。
  • chat.stackoverflow.com/rooms/82768/android-question 想问你一些事情,很高兴你能帮忙,在聊天中阅读。稍后将删除评论。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-28
  • 2012-02-21
  • 2023-04-03
相关资源
最近更新 更多