当前位置: 首页 > 知识库问答 >
问题:

Android-使用AnimatorSet缩放动画

严正诚
2023-03-14

官方缩放视图教程使用AnimatorSet缩放到View。它会随着视图的扩展而产生向下移动的错觉。稍后,只需向后重播AnimatorSet即可产生缩小的错觉。

以下是我目前为止尝试过的。我的XML布局是

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent">

<LinearLayout android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:background="#1999da">             

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:orientation="horizontal"
        android:layout_gravity="center"
        android:gravity="center">

        <!-- The final shrunk image -->

        <ImageView
            android:id="@+id/thumb_button_1"
            android:layout_width="wrap_content"
            android:layout_height="50dp"
            android:layout_marginRight="1dp"
            android:visibility="invisible"/>

    </LinearLayout>

</LinearLayout>

<!-- The initial expanded image that needs to be shrunk -->

<ImageView
    android:id="@+id/expanded_image"
    android:layout_width="wrap_content"
    android:layout_height="125dp"
    android:layout_gravity="center"
    android:src="@drawable/title_logo_expanded"
    android:scaleType="centerCrop"/>

</FrameLayout>

这是执行缩小操作的方法。我基本上试着颠倒了教程中的过程:

private void zoomImageFromThumbReverse(final View expandedImageView, int imageResId, final int duration) {
    // If there's an animation in progress, cancel it immediately and proceed with this one.      

    if (mCurrentAnimator != null) {
        mCurrentAnimator.cancel();
    }

    // Load the low-resolution "zoomed-out" image.
    final ImageView thumbView = (ImageView) findViewById(R.id.thumb_button_1);
    thumbView.setImageResource(imageResId);

    // Calculate the starting and ending bounds for the zoomed-in image. This step
    // involves lots of math. Yay, math.
    final Rect startBounds = new Rect();
    final Rect finalBounds = new Rect();
    final Point globalOffset = new Point();

    // The start bounds are the global visible rectangle of the container view (i.e. the FrameLayout), and the
    // final bounds are the global visible rectangle of the thumbnail. Also
    // set the container view's offset as the origin for the bounds, since that's
    // the origin for the positioning animation properties (X, Y).
    findViewById(R.id.container).getGlobalVisibleRect(startBounds, globalOffset);
    thumbView.getGlobalVisibleRect(finalBounds);
    startBounds.offset(-globalOffset.x, -globalOffset.y);
    finalBounds.offset(-globalOffset.x, -globalOffset.y);

    // Adjust the start bounds to be the same aspect ratio as the final bounds using the
    // "center crop" technique. This prevents undesirable stretching during the animation.
    // Also calculate the start scaling factor (the end scaling factor is always 1.0).
    float startScale;
    if ((float) finalBounds.width() / finalBounds.height()
            > (float) startBounds.width() / startBounds.height()) {
        // Extend start bounds horizontally
        startScale = (float) startBounds.height() / finalBounds.height();
        float startWidth = startScale * finalBounds.width();
        float deltaWidth = (startWidth - startBounds.width()) / 2;
        startBounds.left -= deltaWidth;
        startBounds.right += deltaWidth;
    } else {
        // Extend start bounds vertically
        startScale = (float) startBounds.width() / finalBounds.width();
        float startHeight = startScale * finalBounds.height();
        float deltaHeight = (startHeight - startBounds.height()) / 2;
        startBounds.top -= deltaHeight;
        startBounds.bottom += deltaHeight;
    }

    // Hide the expanded-image and show the zoomed-out, thumbnail view. When the animation begins,
    // it will position the zoomed-in view in the place of the thumbnail.
    expandedImageView.setAlpha(0f);
    thumbView.setVisibility(View.VISIBLE);

    // Set the pivot point for SCALE_X and SCALE_Y transformations to the top-left corner of
    // the zoomed-in view (the default is the center of the view).
    thumbView.setPivotX(0f);
    thumbView.setPivotY(0f);

    // Construct and run the parallel animation of the four translation and scale properties
    // (X, Y, SCALE_X, and SCALE_Y).
    AnimatorSet set = new AnimatorSet();
    set
            .play(ObjectAnimator.ofFloat(thumbView, View.X, startBounds.left,
                    finalBounds.left))
            .with(ObjectAnimator.ofFloat(thumbView, View.Y, startBounds.top,
                    finalBounds.top))
            .with(ObjectAnimator.ofFloat(thumbView, View.SCALE_X, startScale, 1f))
            .with(ObjectAnimator.ofFloat(thumbView, View.SCALE_Y, startScale, 1f));
    //set.setDuration(mShortAnimationDuration);
    set.setDuration(duration);
    set.setInterpolator(new DecelerateInterpolator());
    set.addListener(new AnimatorListenerAdapter() {
        @Override
        public void onAnimationEnd(Animator animation) {
            mCurrentAnimator = null;
        }

        @Override
        public void onAnimationCancel(Animator animation) {
            mCurrentAnimator = null;
        }
    });
    set.start();
    mCurrentAnimator = set;

    // Upon clicking the zoomed-out image, it should zoom back down to the original bounds
    // and show the thumbnail instead of the expanded image.
    final float startScaleFinal = startScale;
    thumbView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (mCurrentAnimator != null) {
                mCurrentAnimator.cancel();
            }

            // Animate the four positioning/sizing properties in parallel, back to their
            // original values.
            AnimatorSet set = new AnimatorSet();
            set
                    .play(ObjectAnimator.ofFloat(thumbView, View.X, startBounds.left))
                    .with(ObjectAnimator.ofFloat(thumbView, View.Y, startBounds.top))
                    .with(ObjectAnimator
                            .ofFloat(thumbView, View.SCALE_X, startScaleFinal))
                    .with(ObjectAnimator
                            .ofFloat(thumbView, View.SCALE_Y, startScaleFinal));
            //set.setDuration(mShortAnimationDuration);
            set.setDuration(duration);
            set.setInterpolator(new DecelerateInterpolator());
            set.addListener(new AnimatorListenerAdapter() {
                @Override
                public void onAnimationEnd(Animator animation) {
                    expandedImageView.setAlpha(1f);
                    thumbView.setVisibility(View.GONE);
                    mCurrentAnimator = null;
                }

                @Override
                public void onAnimationCancel(Animator animation) {
                    expandedImageView.setAlpha(1f);
                    thumbView.setVisibility(View.GONE);
                    mCurrentAnimator = null;
                }
            });
            set.start();
            mCurrentAnimator = set;
        }
    });
}

我在onCreate()中调用此方法,如下所示:

final View expandedImageView = findViewById(R.id.expanded_image);
new Handler().postDelayed(new Runnable(){
        public void run() {
            zoomImageFromThumbReverse(expandedImageView, R.drawable.title_logo_min, 1000);
        }}, 1000);

好了,就是这样,伙计们。它不起作用。我不知道为什么。演示示例运行完美,那么为什么这个不起作用呢?看看,告诉我我是否疯了。

有人能识别错误吗?或者给我指出正确的方向?我们将非常感谢所有的帮助。

共有2个答案

宗沛
2023-03-14

好吧,我认为您希望从图像和描述中向上移动来缩小。我无法理解你的代码,这对我来说似乎太复杂了(我是一个菜鸟)。现在,我已使用以下代码完成了您想要的操作。首先,我用图像视图声明一个相对布局,这个相对布局将是容器。我设置了初始宽度高度,但我们稍后将从代码中更改它。

<RelativeLayout
    android:id="@+id/container"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity">


    <ImageView
        android:id="@+id/imageView"
        android:layout_width="400dp"
        android:layout_height="200dp"
        android:layout_centerHorizontal="true"
        android:scaleType="fitXY"
        android:src="@drawable/my_image"/>
</RelativeLayout>

现在,在活动中,我为布局更改设置了一个侦听器,以便可以获取容器的实际大小。然后设置图像视图的布局。

public class MainActivity extends Activity {
    ImageView im;
    RelativeLayout container;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Logger.init().hideThreadInfo().setMethodCount(0);

        setContentView(R.layout.activity_main);
        im = (ImageView) findViewById(R.id.imageView);
        container = (RelativeLayout) findViewById(R.id.container);
        container.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                setInitialPos();
                container.getViewTreeObserver().removeOnGlobalLayoutListener(this);
            }
        });

    }

    int width;
    int height;
    int topMargin;

    private void setInitialPos() {
        Logger.e("container: " + container.getWidth() + " x " + container.getHeight());
        width = container.getWidth();
        height = 400;
        RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) im.getLayoutParams();
        layoutParams.width = width;
        layoutParams.height = height;
        topMargin = (container.getHeight() - height) / 2;
        layoutParams.topMargin = topMargin;
        im.setLayoutParams(layoutParams);

        startAnimation();
    }

我们必须在这里动画三件事,宽度,高度和上边距(定位)。因此,我为动画师初始位置声明了三个变量,并在初始布局设置时计算它们。现在我们需要同时激活这三个变量,这很容易。

    private void startAnimation() {
        AnimatorSet animator = new AnimatorSet();

        Animator widthAnimator = ObjectAnimator.ofInt(this, "width", width, 200);
        widthAnimator.setInterpolator(new LinearInterpolator());

        Animator heightAnimator = ObjectAnimator.ofInt(this, "height", height, 100);
        heightAnimator.setInterpolator(new LinearInterpolator());

        Animator marginAnimator = ObjectAnimator.ofInt(this, "topMargin", topMargin, 0);
        marginAnimator.setInterpolator(new LinearInterpolator());

        animator.playTogether(widthAnimator, heightAnimator, marginAnimator);
        animator.setDuration(3000);
        animator.start();
    }

    public void setWidth(int w) {
        RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) im.getLayoutParams();
        layoutParams.width = w;
        im.setLayoutParams(layoutParams);
    }

    public void setHeight(int h) {
        RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) im.getLayoutParams();
        layoutParams.height = h;
        im.setLayoutParams(layoutParams);
    }

    public void setTopMargin(int m) {
        RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) im.getLayoutParams();
        layoutParams.topMargin = m;
        im.setLayoutParams(layoutParams);
    }
}
颛孙智勇
2023-03-14

这是我最终使用的解决方案:

private void applyAnimation(final View startView, final View finishView, long duration) {
    float scalingFactor = ((float)finishView.getHeight())/((float)startView.getHeight());

    ScaleAnimation scaleAnimation =  new ScaleAnimation(1f, scalingFactor,
                                                        1f, scalingFactor,
                                                        Animation.RELATIVE_TO_SELF, 0.5f,
                                                        Animation.RELATIVE_TO_SELF, 0.5f);

    scaleAnimation.setDuration(duration);
    scaleAnimation.setInterpolator(new AccelerateDecelerateInterpolator());

    Display display = getWindowManager().getDefaultDisplay();

    int H;

    if(Build.VERSION.SDK_INT >= 13){
        Point size = new Point();
        display.getSize(size);
        H = size.y;
    }
    else{
        H = display.getHeight();
    }

    float h = ((float)finishView.getHeight());

    float verticalDisplacement = (-(H/2)+(3*h/4));

    TranslateAnimation translateAnimation = new TranslateAnimation(Animation.ABSOLUTE, 0,
                                                                   Animation.ABSOLUTE, 0,
                                                                   Animation.ABSOLUTE, 0,
                                                                   Animation.ABSOLUTE, verticalDisplacement);

    translateAnimation.setDuration(duration);
    translateAnimation.setInterpolator(new AccelerateDecelerateInterpolator());

    AnimationSet animationSet = new AnimationSet(false);
    animationSet.addAnimation(scaleAnimation);
    animationSet.addAnimation(translateAnimation);
    animationSet.setFillAfter(false);

    startView.startAnimation(animationSet);
}

这里的关键因素是<code>TranslateAnimation

toYDelta = (-(H/2)+(3*h/4));

最重要的是要理解为什么这样做。剩下的大部分都很简单。

 类似资料:
  • 我正在使用<code>AnimatorSet 代码如下: 编辑: 我正在使用新的动画API,所以< code > setfillfafter()在这里无法工作。

  • 问题内容: 我正在学习如何制作动态壁纸,但是我有一个困境,我敢肯定所有刚开始的人也都有。 分辨率屏幕的尺寸太多了,如何仅用一套代码就所有版本的代码进行缩放?我知道它已经完成了,因为我在很多APK中都看到了APK中的图像,并对其进行了缩放。 如果只是一幅图像,不需要任何简单的定位,但是我的问题是我必须重新调整背景图像的大小以适合所有设备,那么我的动画也适合该背景上某个x和y位置图像就位,因此看起来好

  • 我已经试了好几个小时了,我觉得是时候放弃了。如何循环XML中定义的AnimatorSet? 我在单个上尝试了、和的几十种组合,但这不是正确的方法。 但它就是不起作用:被调用一次,动画被重复,然后就不再被调用了。 这里的其他类似问题涉及错误答案(指框架),或者建议为单个定义自定义插值器,但这并不是我真正要找的。谢谢你。

  • 使用Google Maps Android API v2在地图上添加一些标记时,标记不会设置到正确的位置,并且在缩放时会移动。 放大时,它们会更接近正确的位置,就好像它们是通过与缩放相关的因子进行转换的一样。 怎么了? 放大示例: 碎片 布局图

  • 问题内容: 我有一个带有RelativeLayout和的私有类的活动,它扩展了。在onScale听众的方法中,我想通过用户展开/捏手指来放大/缩小整个布局(用户看到的一切)。 我想改变的布局不被永久的,即当病毒/捏合手势是在我想的布局回去这是什么在首位(任何复位可能在做onScaleEnd的方法SimpleOnScaleGestureListener例如)。 我试图通过调用和在上以及还使用来实现它

  • 问题内容: 这里是我想要的描述:在tkinter画布中绘制几何对象(在此为矩形)的集合,然后蜜蜂通过鼠标探索该画布。单击并拖动以移动画布,滚动放大和缩小。 使用本主题,我找到了单击和拖动部分:使用Mousewith-mouse 移动tkinter画布 我设法写了一些滚动缩放。移动和缩放都可以很好地分开工作。 问题 :如果移动然后放大,则变焦的焦点不再是光标所在的位置。 有什么建议吗? 这是一段要测