不过为了之后的平移,要保证图片的宽度比View的宽度大
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 ();
}