Android ScaleAnimation to Center of Rect

Android ScaleAnimation to Center of Rect

我正在尝试使用 ScaleAnimation 对象缩放到放置在 Android 中 RelativeLayout 中的 Rect 的中心。

注意:Rect 高度等于 containerView 的高度,所以只是试图找到 pivotXValue,pivotYValue 是中心的 0.5F。 PivotY 工作正常。

我正在尝试获取 Rect 的中心,然后将其除以视图的宽度以获得 pivotXValue,然后在 ScaleAnimation 构造函数中使用它。

我可以添加 Rect 并准确查看它的位置,只是为了调试它。而且它不会缩放到 Rect 的中心。根据 rect 是在 containerView 中心的左侧还是右侧,"zoom point" 似乎分别向右或向左偏移更多。

即:

Rect越靠左,越靠containerView的中间,ScaleAnimation的"zoom point"的偏移似乎越靠右。

Rect越往右越靠containerView的中间,ScaleAnimation的"zoom point"的偏移似乎越靠左

代码如下:

val zoomScale = 2.0F

val pivotXReference = zoomRect.right - (zoomRect.width() / 2F)

val pivotXValue = pivotXReference / containerView.width.toFloat()

val scaleAnim = ScaleAnimation(
                1f,
                zoomScale,
                1f,
                zoomScale,
                Animation.RELATIVE_TO_SELF,
                pivotXValue,
                Animation.RELATIVE_TO_SELF,
                0.5F)

scaleAnim.duration = 250
scaleAnim.fillAfter = true
containerView.animation = scaleAnim

我放弃了 ScaleAnimation,因为我永远无法理解它,而且我了解到它不会更新视图本身的属性,只会更新绘图,这不是我需要的。

我使用 ObjectAnimator class 解决了这个问题。它按我的意愿缩放并落在矩形的中心:

        val pivotXReference = zoomRect.right - (zoomRect.width() / 2)

        val anim = ObjectAnimator.ofFloat(fretboardView, "scaleX", zoomScale)
        anim.duration = 250

        val anim2 = ObjectAnimator.ofFloat(fretboardView, "scaleY", zoomScale)
        anim2.duration = 250

        // It was scaled at the center, so minus /2 offsets it to 0, then subtract how "right" you want to offset the x position
        val animX = ((fretboardView.width * zoomScale) / 2) - (pivotXReference.toFloat() * zoomScale)
        val anim3 = ObjectAnimator.ofFloat(fretboardView, "x", animX)
        anim3.duration = 250

        val animSetXY = AnimatorSet()
        animSetXY.playTogether(anim, anim2, anim3)
        animSetXY.start()