How to rotate image in imageview on button click each time?

自闭症网瘾萝莉.ら 提交于 2020-01-11 04:41:07

问题


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


        }
    });



}

回答1:


Change your onClick() method to

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

Notice, what the docs say

Sets the degrees that the view is rotated around the pivot point. Increasing values result in clockwise rotation.


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

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.



来源:https://stackoverflow.com/questions/28259534/how-to-rotate-image-in-imageview-on-button-click-each-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!