How to rotate image in imageview on button click each time?(如何在每次单击按钮时在 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 说什么
设置视图围绕枢轴点旋转的度数.增加值会导致顺时针旋转.
Sets the degrees that the view is rotated around the pivot point. Increasing values result in clockwise rotation.
<小时>
如果您还针对运行 Gingerbread (v10) 或更低版本的 Android 设备,我想更新我的答案以展示如何使用 RotateAnimation
来实现相同的效果.
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 中旋转图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在每次单击按钮时在 imageview 中旋转图像?


基础教程推荐
- 如何在 Spring @Value 注解中正确指定默认值? 2022-01-01
- 在 Java 中创建日期的正确方法是什么? 2022-01-01
- 验证是否调用了所有 getter 方法 2022-01-01
- 从 python 访问 JVM 2022-01-01
- Java 实例变量在两个语句中声明和初始化 2022-01-01
- Java Swing计时器未清除 2022-01-01
- 大摇大摆的枚举 2022-01-01
- 不推荐使用 Api 注释的描述 2022-01-01
- 如何在 JFrame 中覆盖 windowsClosing 事件 2022-01-01
- 多个组件的复杂布局 2022-01-01