Android scale animation on view

前端 未结 7 1032
轮回少年
轮回少年 2020-11-28 04:10

I want to use ScaleAnimation (programmatically not in xml) to change height to view from 0 to 60% of parent height. Width of view is constant and is 50px. View is empty onl

7条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-28 04:32

    Here is a code snip to do exactly that.

    public void scaleView(View v, float startScale, float endScale) {
        Animation anim = new ScaleAnimation(
                1f, 1f, // Start and end values for the X axis scaling
                startScale, endScale, // Start and end values for the Y axis scaling
                Animation.RELATIVE_TO_SELF, 0f, // Pivot point of X scaling
                Animation.RELATIVE_TO_SELF, 1f); // Pivot point of Y scaling
        anim.setFillAfter(true); // Needed to keep the result of the animation
        anim.setDuration(1000);
        v.startAnimation(anim);
    }
    

    The ScaleAnimation constructor used here takes 8 args, 4 related to handling the X-scale which we don't care about (1f, 1f, ... Animation.RELATIVE_TO_SELF, 0f, ...).

    The other 4 args are for the Y-scaling we do care about.

    startScale, endScale - In your case, you'd use 0f, 0.6f.

    Animation.RELATIVE_TO_SELF, 1f - This specifies where the shrinking of the view collapses to (referred to as the pivot in the documentation). Here, we set the float value to 1f because we want the animation to start growing the bar from the bottom. If we wanted it to grow downward from the top, we'd use 0f.

    Finally, and equally important, is the call to anim.setFillAfter(true). If you want the result of the animation to stick around after the animation completes, you must run this on the animator before executing the animation.

    So in your case, you can do something like this:

    View v = findViewById(R.id.viewContainer);
    scaleView(v, 0f, .6f);
    

提交回复
热议问题