前言
大家在音乐类app中,经常看到类似唱片的旋转动画。如何利用 属性动画 ObjectAnimator和 补间动画 RotateAnimation 分别实现这一效果呢?
用ObjectAnimator实现
直接上代码
public class MyActivity extends Activity {
@BindView(R.id.id_iv_cover)
CircleImageView idIvCover;
private ObjectAnimator mAnimator;
public static final int STATE_PLAYING = 1;//正在播放
public static final int STATE_PAUSE = 2;//暂停
public static final int STATE_STOP = 3;//停止
public int mState;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
protected void initView() {
setContentView(R.layout.activity_my);
ButterKnife.bind(this);
initAnimator();
idIvCover.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
playMusic();
}
});
}
public void playMusic() {
if (mState == STATE_STOP) {
mAnimator.start();//动画开始
mState = STATE_PLAYING;
} else if (mState == STATE_PAUSE) {
mAnimator.resume();//动画重新开始
mState = STATE_PLAYING;
} else if (mState == STATE_PLAYING) {
mAnimator.pause();//动画暂停
mState = STATE_PAUSE;
}
}
private void initAnimator() {
mState = STATE_STOP;
mAnimator = ObjectAnimator.ofFloat(idIvCover, "rotation", 0.0f, 360.0f);
mAnimator.setDuration(5000);//设定转一圈的时间
mAnimator.setRepeatCount(Animation.INFINITE);//设定无限循环
mAnimator.setRepeatMode(ObjectAnimator.RESTART);// 循环模式
mAnimator.setInterpolator(new LinearInterpolator());// 匀速
}
}