在Android中使用Matrix类旋转ImageView

时间:2016-08-17 07:24:51

标签: android android-imageview

我正在尝试使用ImageView课程围绕它的中心轮换Matrix

这是我的ImageView XML代码

<ImageView
    android:id="@+id/carBack"
    android:layout_width="200dp"
    android:layout_height="200dp"
    android:src="@drawable/automodel"/>

这是我在SO上找到的旋转ImageView

的方法
Matrix matrixX = new Matrix();
mCarBack.setScaleType(ImageView.ScaleType.MATRIX);   //required
float pivotXBack = mCarBack.getDrawable().getBounds().width()/2;
float pivotYBack = mCarBack.getDrawable().getBounds().height()/2;
matrixX.postRotate((float) byteRoll, pivotXBack, pivotYBack);
mCarBack.setImageMatrix(matrixX);

旋转正常,但我的ImageView会自动调整大小。如何旋转图像视图保持相同的大小?

1 个答案:

答案 0 :(得分:0)

试试这个:

try {


//Get ImageView from layout xml file
img = (ImageView) findViewById(R.id.imageView01);

//Decode Image using Bitmap factory.
//Bitmap bMapimg = BitmapFactory.decodeFile(selectedImagePath);
 Bitmap bMapimg = Bitmap.createBitmap(img.getDrawingCache());

//Create object of new Matrix.
Matrix matrix = new Matrix();

//set image rotation value to 90 degrees in matrix.
matrix.postRotate(90);
matrix.postScale(0.5f, 0.5f);

int newWidth = bMap.getWidth()/2;
int newHeight = bMap.getHeight()/2;

//Create bitmap with new values.
Bitmap bMapRotate = Bitmap.createBitmap(bMap, 0, 0, newWidth, newHeight, matrix, true);

//put rotated image in ImageView.
img.setImageBitmap(bMapRotate);

Context context = getApplicationContext();
CharSequence text = "Image Rotated" ;
int durationtime = Toast.LENGTH_SHORT;

Toast toasttext = Toast.makeText(context, text, duration);

toast.show();

 } catch (Exception e) {       
 e.printStackTrace();
 displayExceptionMessage(e.getMessage());
}