Android ScaleAnimation to Center of Rect

I'm trying to zoom to the center of a Rect that is placed in a RelativeLayout in Android by using a ScaleAnimation object.

Note: The Rect height is EQUAL to the height of the containerView, so just trying to find the pivotXValue, pivotYValue is 0.5F for the center. PivotY is working fine.

I'm trying to get the center of the Rect, and then divide it by the width of the view to get the pivotXValue, which I then use in the ScaleAnimation constructor.

I can add the Rect and see exactly where it is just to debug this. And it will not zoom to the center of the Rect. Depending on whether the rect is to the left or right of the center of the containerView, the "zoom point" will seem to offset more to the right or left respectively.

That is:

The more Rect is past, to the LEFT, of the middle of the containerView, the more RIGHT the offset of the "zoom point" of the ScaleAnimation seems to be.

The more Rect is past, to the RIGHT, of the middle of the containerView, the more LEFT the offset of the "zoom point" of the ScaleAnimation seems to be.

Here's the code:

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

I ditched ScaleAnimation as I could never figure it out, plus I learned it does not update the properties of the view itself, only the drawing, which is not what I needed.

I solved it by using the ObjectAnimator class. It zooms and lands right in the center of the rect as I wanted:

        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()
链接地址: http://www.djcxy.com/p/42608.html

上一篇: C ++共享库显示内部符号

下一篇: Android ScaleAnimation到Rect的中心