如何正确设置路径值以描述Android中的弧形动画

问题描述 投票:0回答:1

我在按钮内有一个视图“ whiteCircle”,我希望将其从其初始位置移至描述弧的白框“ imageSquared”,然后返回其初始位置。

我尝试过的是:

private fun startArcAnimation() {

    val path = Path()

    val location = IntArray(2)
    imageSquared.getLocationOnScreen(location)

    path.arcTo(
        0f,
        0f,
        location[0].toFloat() + imageSquared.width,
        location[0].toFloat() + imageSquared.height,
        180f,
        180f,
        true
    )

    val animator = ObjectAnimator.ofFloat(whiteCircle, View.X, View.Y, path)
    animator.duration = 1000
    animator.start()

}

这是结果:

enter image description here

您能帮我设置正确的路径值吗?我一直在努力使用arcTo属性,但没有成功。

提前感谢。

android android-animation
1个回答
1
投票

这是我的实现:

gif

arcTo方法创建放置在矩形中的椭圆。因此,首先您需要创建正确的矩形。您的路径应从椭圆形的180度开始,然后顺时针移动180度(椭圆形的零角度位于右侧)。

scheme

我建议为视图的translationXtranslationY属性设置动画。

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        greenButton.setOnClickListener {
            startArcAnimation()
        }
    }

    private fun startArcAnimation() {
        if (red.translationX != 0f) {
            //return to start position animation
            red.animate().translationX(0f).translationY(0f).start()
            return
        }

        val rectHeight = 600
        val left = 0f
        val top = -rectHeight / 2
        val right = white.x - red.x
        val bottom = white.y + rectHeight / 2 - red.y

        val path = Path()
        path.arcTo(left, top.toFloat(), right, bottom, 180f, 180f, true)

        val animator = ObjectAnimator.ofFloat(red, View.TRANSLATION_X, View.TRANSLATION_Y, path)
        animator.duration = 1000
        animator.start()
    }
}

这里是activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#000"
    android:padding="16dp">

    <Button
        android:id="@+id/greenButton"
        android:layout_width="100dp"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical"
        android:background="#0a0"
        android:stateListAnimator="@null" />

    <ImageView
        android:id="@+id/white"
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:layout_gravity="center_vertical|right"
        android:background="#fff" />

    <ImageView
        android:id="@+id/red"
        android:layout_width="20dp"
        android:layout_height="20dp"
        android:layout_gravity="center_vertical"
        android:layout_marginLeft="70dp"
        android:layout_marginBottom="10dp"
        android:background="#f00" />

</FrameLayout>
© www.soinside.com 2019 - 2024. All rights reserved.