之前一次面试时,问道要实现一个效果,点击一个圆形头像放大移动跳转到另一个Activity同一图片位置,好使没有跳转痕迹。当时就简单说了一下,没有深入,今天有空就自己实现了一下。
我的想法是点击头像放大移动到固定位置,然后activity再跳转。
考虑到头像位置不一定是固定的,所以每次跳转时需要重新计算一下移动参数。动画结束时还需要有个淡入和淡出的效果
首先是准备一个缩放的动画。第一个activity里的图片尺寸按100×100,第二个activity的尺寸是300×300,所以放大的倍数是固定为3倍
那第一个动画的代码
Animation animate1 = new ScaleAnimation(1.0f, 3.0f, 1.0f, 3.0f,
Animation.RELATIVE_TO_SELF, 0.5f,
Animation.RELATIVE_TO_SELF, 0.5f);
重点在第二个移动的动画,由于位置不是固定的,所以要将图片从现有位置移动到你需要它移动到的位置
第一步拿到屏幕的宽和高
int width = getResources().getDisplayMetrics().widthPixels;
int height = getResources().getDisplayMetrics().heightPixels;
不过由于状态栏还占着一定的高度所以要减去这部分
Rect frame = new Rect();
getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
int notifiheight = frame.top;
int height = getResources().getDisplayMetrics().heightPixels - notifiheight;
第二步计算图片在x轴和y轴上的位移
因为我们最终是要将头像移动到屏幕的正中间位置。那x轴的计算方法就很简单了,屏幕的宽度的一半减去头像在x轴的位置,在减去头像中心点的x位移坐标
final float fromx = img_girl.getPivotX();
final float tox = width / 2 - fromx - img_girl.getX();
而y轴就有所不同。因为布局用了ScrollView,y轴方向上是可滑动的,所以还需加上y轴的滑动距离
int sheight = sv_main.getScrollY();
final float fromy = img_girl.getPivotY();
final float toy = sheight + height / 2 - fromy - img_girl.getY();
第三步实现位移动画
Animation animate2 = new TranslateAnimation(0, tox, 0, toy);
启动动画
AnimationSet set = new AnimationSet(true);
set.setFillAfter(true);
set.addAnimation(animate1);
set.addAnimation(animate2);
set.setDuration(500);
img_girl.startAnimation(set);
启动动画时一定要
set.setFillAfter(true);
不然动画结束后头像自动变回原有尺寸和位置,影响效果 开始动画后还要做监听,在动画结束时进行两个Activity的淡入淡出效果
set.setAnimationListener(new Animation.AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
}
@Override
public void onAnimationEnd(Animation animation) {
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
startActivity(intent);
overridePendingTransition(R.anim.tran_in, R.anim.tran_out);
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
Animation animate3 = new ScaleAnimation(fromx, fromx, fromy, fromy);
AnimationSet set2 = new AnimationSet(true);
set2.addAnimation(animate3);
set2.setDuration(0);
img_girl.startAnimation(set2);
}
}, 500);
}
@Override
public void onAnimationRepeat(Animation animation) {
}
});
淡入和淡出的动画
tran_in.xml
<set xmlns:android="http://schemas.android.com/apk/res/android" >
<alpha
android:duration = "500"
android:fromAlpha="0.5"
android:toAlpha="1.0"/>
</set>
tran_out.xml
<set xmlns:android="http://schemas.android.com/apk/res/android">
<alpha
android:duration="500"
android:fromAlpha="1"
android:toAlpha="0.5" />
</set>
http://download.csdn.net/detail/u013898922/9903494