java - 在android中旋转图像中心而不是宽圆圈
问题描述
我有一个 ImageView 和 Button。按钮视图位于屏幕底部。ImageView 位于按钮上方。当我单击按钮时,图像应移动到屏幕中心。移动到中心后,单击图像应该旋转。但在我的情况下,它以更宽的圆圈旋转,而不是在中心旋转。
我正在使用下面的代码。
<ImageView
android:id="@+id/image"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:scaleType="centerCrop"
android:visibility="visible" />
<Button
android:id="@+id/button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:text="Start" />
点击按钮后,移动到屏幕中心
image.animate().y(metrics.heightPixels / 2 - image.getHeight() / 2).x(metrics.widthPixels / 2 - image.getWidth() / 2)
在上述步骤之后旋转图像。
RotateAnimation animRotate = new RotateAnimation(0.0f, 360.0f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
animRotate.setDuration(duration);
animRotate.setInterpolator(new DecelerateInterpolator(1.5f));
image.startAnimation(animRotate)
它不是在中心旋转,而是像更宽的圆圈一样旋转。你能帮我吗。
解决方案
视图的翻译发生在布局后。结果是,尽管视图出现在新位置(翻译后位置),但旋转动画仍然认为视图处于其原始位置(其布局位置)。您看到视图以大圆圈旋转,因为旋转中心是视图的预平移中心。为什么这对我来说是一个永恒的谜。
为了解决这个问题,您需要计算屏幕上显示的视图的真实中心。以下代码显示了如何做到这一点。视图从屏幕中心平移到左上角并原地旋转。(您不必使用全局布局侦听器。)
// Wait until everything is laid out before we can manipulate it.
image.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
int duration = 1000;
@Override
public void onGlobalLayout() {
image.getViewTreeObserver().removeOnGlobalLayoutListener(this);
// Save the initial location of the top-left corner of the view.
float initX = image.getX();
float initY = image.getY();
image.animate().y(0).x(0).setDuration(duration).withEndAction(new Runnable() {
@Override
public void run() {
// The post-translation center of the view is at the new top-left corner
// plus 1/2 the width and height of the view. We need to compute the
// displacement from the original center to feed into the RotationAnimation.
RotateAnimation animRotate =
new RotateAnimation(0.0f, 360.0f,
Animation.ABSOLUTE, image.getX() - initX + (image.getWidth() / 2f),
Animation.ABSOLUTE, image.getY() - initY + (image.getHeight() / 2f));
animRotate.setDuration(duration);
image.startAnimation(animRotate);
}
});
}
});
推荐阅读
- javascript - 手风琴只打开一次然后出现故障
- python - 在 Windows 10 上安装 cusignal
- java - 如何在 Java 中的 if 语句中使用事件对象作为条件?
- git - Git切换分支忽略分支名称大小写
- c++ - AWS SDK C++ 安装/Embarcadero:CMake 错误 -fPIC
- php - 两个不同变量中的 PHP 数组
- node.js - 我想为每个虚拟应用程序托管 nodejs 实例,在 azure app 服务中只有一个文件夹的物理位置
- graphql - 带有命名空间查询的 Apollo Client 3.0 缓存
- javascript - JavaScript 自动图像幻灯片放映错误
- .net - .NET 的后写缓存的 Redis 可扩展性