本文主要是介绍Android中用Matrix实现ImageView里的图片平移和缩放动画,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
注: 这里说的图片的平移和缩放不是对ImageView整个view进行的,而是对ImageView里面的图片进行的(view本身没有什么变化),所以Android自带的动画效果不能满足需求。public void setImage ( Drawable drawable ) {
if ( null == drawable ) return;
int dwidth = drawable.getIntrinsicWidth ();
int dheight = drawable.getIntrinsicHeight ();
int vwidth = mWidth;
int vheight = mHeight;
float scale = 1.0f;
float dx = 0, dy = 0;
if ( dwidth * vheight > vwidth * dheight ) {
scale = ( float ) vheight / ( float ) dheight;
dx = ( vwidth - dwidth * scale ) * 0.5f + 0.5f;
} else {
scale = ( float ) vwidth / ( float ) dwidth;
dy = ( vheight - dheight * scale ) * 0.5f + 0.5f;
}
if ( dwidth * scale < 2 * vwidth ) {
scale = ( float ) vwidth / ( 2.0f * dwidth );
dx = - dwidth / 2;
dy = ( vheight - dheight * scale ) * 0.5f + 0.5f;
}
Matrix matrix = new Matrix ();
matrix.setScale ( scale, scale );
matrix.postTranslate ( dx, dy );
mImage.setImageMatrix ( matrix );
mImage.setImageDrawable ( drawable );
}
// vwidth和vheight使用确定的值,因为如果在应用初始化时view.getWidth()可能为0
private class MyTransXAnimatorListener implements AnimatorUpdateListener {
private Matrix mPrimaryMatrix;
public MyTransXAnimatorListener ( Matrix matrix ) {
mPrimaryMatrix = new Matrix ( matrix );
}
@Override
public void onAnimationUpdate ( ValueAnimator animation ) {
int dx = ( Integer ) animation.getAnimatedValue ();
Matrix matrix = new Matrix ( mPrimaryMatrix );
matrix.postTranslate ( dx, 0 );
mImage.setImageMatrix ( matrix );
}
}
public void setTranslateAnimation () {
ValueAnimator animator = ValueAnimator.ofInt ( 0, - 60 );
animator.addUpdateListener ( new MyTransXAnimatorListener ( mImage.getImageMatrix() ) );
animator.setDuration ( 1000 );
animator.setInterpolator ( new DecelerateInterpolator () );
animator.setStartDelay ( 500 );
animator.start ();
}
private class MyScaleAnimatorListener implements AnimatorUpdateListener {
private Matrix mPrimaryMatrix;
public MyScaleAnimatorListener ( Matrix matrix ) {
mPrimaryMatrix = matrix;
}
@Override
public void onAnimationUpdate ( ValueAnimator animation ) {
float scale = ( Float ) animation.getAnimatedValue ();
Matrix matrix = new Matrix ( mPrimaryMatrix );
matrix.postScale ( scale, scale, mWidth / 2, mHeight / 2 );
mImage.setImageMatrix ( matrix );
}
}
public void setScaleAnimation () {
ValueAnimator animator = ValueAnimator.ofFloat ( 1.0f, 1.2f );
animator.addUpdateListener ( new MyScaleAnimatorListener ( mImage.getImageMatrix () ) );
animator.setDuration ( 1000 );
animator.setInterpolator ( new DecelerateInterpolator () );
animator.setStartDelay ( 500 );
animator.start ();
}
这篇关于Android中用Matrix实现ImageView里的图片平移和缩放动画的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!