Animation series: java code to achieve picture zoom animation

  • Directly upload the renderings:
  • The core problem of zoom animation is not how to set the animation, but how to get the center point of the picture. The default focus of the zoom animation is the upper left corner of the picture, that is, the picture is stretched to the bottom right. We must find a way to get the coordinates of the center of the picture.

  • First experience the situation where the focus is in the upper left corner:
public class MainActivity extends AppCompatActivity {

    ImageView iv;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        iv = findViewById(R.id.iv);
        ScaleAnimation scaleAnimation2 = new ScaleAnimation(1f, 2f, 1f, 2f,
                ScaleAnimation.ABSOLUTE,
                iv.getWidth() / 2f,
                ScaleAnimation.ABSOLUTE,
                iv.getHeight() / 2f);
        scaleAnimation2.setDuration(2000);
        //设置动画结束之后的状态是否是动画开始时的状态,true,表示是保持动画开始时的状态
        scaleAnimation2.setFillBefore(true);
        //设置reverse的效果是先放大,再缩小。设置restart的效果是先放大,瞬间变小,再放大。
        scaleAnimation2.setRepeatMode(ScaleAnimation.REVERSE);
        scaleAnimation2.setRepeatCount(ScaleAnimation.INFINITE);
        iv.startAnimation(scaleAnimation2);
    }
}

Did you find that the focus is on the upper left corner? iv.getWidth() got 0. Not much BB, zoom in.

  • Final solution

public class MainActivity extends AppCompatActivity {
    ImageView iv;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        iv = findViewById(R.id.iv);
        iv.post(new Runnable() {
            @Override
            public void run() {
                ScaleAnimation scaleAnimation2 = new ScaleAnimation(1f, 2f, 1f, 2f,
                        ScaleAnimation.ABSOLUTE,
                        iv.getWidth() / 2f,
                        ScaleAnimation.ABSOLUTE,
                        iv.getHeight() / 2f);
                scaleAnimation2.setDuration(2000);
                //设置动画结束之后的状态是否是动画开始时的状态,true,表示是保持动画开始时的状态
                scaleAnimation2.setFillBefore(true);
                //设置reverse的效果是先放大,再缩小。设置restart的效果是先放大,瞬间变小,再放大。
                scaleAnimation2.setRepeatMode(ScaleAnimation.REVERSE);
                scaleAnimation2.setRepeatCount(ScaleAnimation.INFINITE);
                iv.startAnimation(scaleAnimation2);
            }
        });
    }
}

Guess you like

Origin blog.csdn.net/zhangjin1120/article/details/113732439