android 图片动态移动,使用动画移动视图 | Android 开发者 | Android Developers
屏幕上的对象通常需要重新定位。这种情况可能是由于用户互动或幕后进行某些处理而导致的。您应使用动画将对象从起始位置移动到结束位置,而不应立即更新对象位置,立即更新对象位置会使对象从一个区域闪跳到另一个区域。Android 提供了一些可让您在屏幕上重新定位视图对象的方法,例如 ObjectAnimator。您可以提供希望对象停留的结束位置,以及动画的持续时间。您可以将此方法与时间插值器结合使用,以控制
屏幕上的对象通常需要重新定位。这种情况可能是由于用户互动或幕后进行某些处理而导致的。您应使用动画将对象从起始位置移动到结束位置,而不应立即更新对象位置,立即更新对象位置会使对象从一个区域闪跳到另一个区域。
Android 提供了一些可让您在屏幕上重新定位视图对象的方法,例如 ObjectAnimator。您可以提供希望对象停留的结束位置,以及动画的持续时间。您可以将此方法与时间插值器结合使用,以控制动画的加速或减速。
使用 ObjectAnimator 更改视图位置
translationX 和 translationY 属性。
以下示例
Kotlin
ObjectAnimator.ofFloat(view, "translationX", 100f).apply {
duration = 2000
start()
}Java
ObjectAnimator animation = ObjectAnimator.ofFloat(view, "translationX", 100f);
animation.setDuration(2000);
animation.start();
此示例使用 ObjectAnimator.ofFloat() 方法,因为平移值必须是浮点值。第一个参数是您想要添加动画的视图。第二个参数是您要添加动画的属性。由于需要水平移动视图,因此使用了 translationX 属性。最后一个参数是动画的结束值。该值为 100,表示距离屏幕左侧的像素数为 100。
下一个方法以毫秒为单位指定动画应持续的时间。在此示例中,动画将运行 2 秒(2000 毫秒)。
最后一个方法用于让动画开始运行,这会更新视图在屏幕上的位置。
添加曲线动作
虽然使用
使用 PathInterpolator
Kotlin
// arcTo() and PathInterpolator only available on API 21+
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
val path = Path().apply {
arcTo(0f, 0f, 1000f, 1000f, 270f, -180f, true)
}
val pathInterpolator = PathInterpolator(path)
}Java
// arcTo() and PathInterpolator only available on API 21+
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
Path path = new Path();
path.arcTo(0f, 0f, 1000f, 1000f, 270f, -180f, true);
PathInterpolator pathInterpolator = new PathInterpolator(path);
}
您也可以将路径插值器定义为 XML 资源:
android:controlX1="0.4"
android:controlY1="0"
android:controlX2="1"
android:controlY2="1"/>
创建
Kotlin
val animation = ObjectAnimator.ofFloat(view, "translationX", 100f).apply {
interpolator = pathInterpolator
start()
}Java
ObjectAnimator animation = ObjectAnimator.ofFloat(view, "translationX", 100f);
animation.setInterpolator(pathInterpolator);
animation.start();
定义您自己的路径
Kotlin
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
val path = Path().apply {
arcTo(0f, 0f, 1000f, 1000f, 270f, -180f, true)
}
val animator = ObjectAnimator.ofFloat(view, View.X, View.Y, path).apply {
duration = 2000
start()
}
} else {
// Create animator without using curved path
}Java
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
Path path = new Path();
path.arcTo(0f, 0f, 1000f, 1000f, 270f, -180f, true);
ObjectAnimator animator = ObjectAnimator.ofFloat(view, View.X, View.Y, path);
animator.setDuration(2000);
animator.start();
} else {
// Create animator without using curved path
}
以下是弧形动画的效果:
如果您不想创建自己的时长或路径曲线,系统为 Material Design 规范中的三条基本曲线提供了 XML 资源:
@interpolator/fast_out_linear_in.xml
@interpolator/fast_out_slow_in.xml
@interpolator/linear_out_slow_in.xml
更多推荐
所有评论(0)