沿图片上边沿为轴线,图片上下摆动旋转
时间: 2023-09-21 11:13:39 浏览: 42
要实现沿图片上边沿为轴线,图片上下摆动旋转,可以使用Matrix和ValueAnimator来实现。以下是一个简单的代码示例:
首先定义一个ImageView来显示图片:
```xml
<ImageView
android:id="@+id/image_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="@drawable/image" />
```
然后在Activity中使用Matrix和ValueAnimator来实现图片的动画效果:
```java
// 获取ImageView和原始图片
ImageView imageView = findViewById(R.id.image_view);
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.image);
// 计算旋转中心点的位置,沿图片上边沿为轴线
int centerX = bitmap.getWidth() / 2;
int centerY = 0;
// 创建Matrix对象,用于进行旋转变换
Matrix matrix = new Matrix();
// 创建ValueAnimator对象,用于控制动画效果
ValueAnimator animator = ValueAnimator.ofInt(0, 360);
animator.setDuration(2000);
animator.setInterpolator(new LinearInterpolator());
animator.setRepeatCount(ValueAnimator.INFINITE);
animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
// 获取当前动画进度
int angle = (int) animation.getAnimatedValue();
// 计算旋转角度和上下摆动的角度
float rotateAngle = angle;
float swingAngle = (float) Math.sin(Math.toRadians(angle)) * 10;
// 设置Matrix变换
matrix.reset();
matrix.postRotate(rotateAngle, centerX, centerY);
matrix.postTranslate(0, swingAngle);
// 设置ImageView的Matrix变换
imageView.setImageMatrix(matrix);
}
});
// 启动动画
animator.start();
```
在上面的代码中,我们首先获取ImageView和原始图片,并计算旋转中心点的位置,沿图片上边沿为轴线。然后创建Matrix对象,用于进行旋转变换。接着创建ValueAnimator对象,用于控制动画效果,设置动画时长、插值器、重复次数和动画更新监听器。在动画更新监听器中,我们获取当前动画进度,计算旋转角度和上下摆动的角度,并使用Matrix的postRotate和postTranslate方法设置Matrix变换。最后,将设置好的Matrix变换应用到ImageView上。
注意,在设置Matrix变换时,需要使用Matrix的reset方法将Matrix重置为单位矩阵,然后再使用postRotate和postTranslate方法进行变换。另外,在计算上下摆动的角度时,我们使用了Math.sin方法来计算正弦值,并乘以10来放大效果。