Java 每次单击按钮时如何在imageview中旋转图像?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28259534/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to rotate image in imageview on button click each time?
提问by user2095748
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.
这是java代码。我从图片库获取图像。我有一个按钮和一个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);
}
});
}
采纳答案by Ravi Thapliyal
Change your onClick()
method to
将您的onClick()
方法更改为
@Override
public void onClick(View v)
{
imageView.setRotation(imageView.getRotation() + 90);
}
Notice, what the docssay
注意,文档说了什么
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.
RotateAnimation
如果您还针对运行 Gingerbread (v10) 或更低版本的 Android 设备,我想更新我的答案以展示如何使用来实现相同的效果。
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 animationsthrough 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.
通常也可以通过 XML设置这样的视图动画。但是,由于您必须在其中指定绝对度数值,因此连续旋转将重复进行,而不是在前一个旋转的基础上完成一个完整的圆。因此,我选择在上面的代码中展示如何做到这一点。