如何在每次按钮点击时在imageview中旋转图像? [英] How to rotate image in imageview on button click each time?

查看:99
本文介绍了如何在每次按钮点击时在imageview中旋转图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

This is java code.I am getting image from image gallery.I have one Button and one ImageView. It is rotating only one time.When I again click button it is not rotating image.

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


        }
    });



}


推荐答案

onClick()方法改为

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

注意, docs


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






我'我想更新我的答案,以显示如何使用 RotateAnimation 来达到同样的效果,以防你的目标是运行Gingerbread(v10)或更低版本的Android设备。


I'd like to update my answer to show how to use RotateAnimation to achieve the same effect in case you're also targeting Android devices running Gingerbread (v10) or below.

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

引入一个实例字段来跟踪上面的旋转度数用它作为:

Introduce an instance field to track the rotation degrees as above and use it as:

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查看动画。但是,由于您必须在那里指定绝对度数值,因此连续旋转将重复自身,而不是构建在前一个上以完成整圆。因此,我选择在上面的代码中展示如何做到这一点。

Usually one can setup such View animations through XML as well. But, since you have to specify absolute degree values in there, successive rotations will repeat themselves instead of building upon the previous one to complete a full circle. Hence, I chose to show how to do it in code above.

这篇关于如何在每次按钮点击时在imageview中旋转图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆