1. 程式人生 > >Android UI之ImageView旋轉的幾種方式

Android UI之ImageView旋轉的幾種方式

我整理了一下,大概有四種,親測成功三種。

第一種,效率較低,不過看許多部落格都使用這種方法,即旋轉bitmap:

Bitmap bitmap = ((BitmapDrawable)getResources().getDrawable(R.drawable.ic_launcher)).getBitmap();
Matrix matrix  = new Matrix();
matrix.setRotate(90);
Bitmap new = Bitmap.create(bitmap,0,bitmap.getWidth(),0,bitmap.getHeight(),matrix);
image.setBitmapResource(bitmap);

如果程式不斷獲取新的bitmap重新設定給ImageView的話,那麼bitmap在不斷旋轉,又不回收記憶體,浪費大大噠,不推薦使用。

第二種,使用ImageView自帶的旋轉方法

可以通過在xml中設定ImageView的屬性來實現,如

android:rotation="90"
,這樣。

動態呼叫如下:

image.setPivotX(image.getWidth()/2);
image.setPivotY(image.getHeight()/2);//支點在圖片中心
image.setRotation(90);

第三種,使用旋轉動畫

可以使用ImageView配合屬性動畫實現,如
rotateImage.animate().rotation(90);
或者普通動畫
Animation rotateAnimation  = new RotateAnimation(lastAngle, progress, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 1);
                rotateAnimation.setFillAfter(true);
                rotateAnimation.setDuration(50);
                rotateAnimation.setRepeatCount(0);
                rotateAnimation.setInterpolator(new LinearInterpolator());
                rotateImage.startAnimation(rotateAnimation);

第四種,其他部落格看到的,未測試!

Matrix matrix=new Matrix();
                rotateImage.setScaleType(ScaleType.MATRIX);   //required
                matrix.postRotate((float) progress, pivotX, pivotY);
                rotateImage.setImageMatrix(matrix);