在我的应用中,我拥有它,以便button
每按一次bitmap
旋转90度。我有另一个button
执行相同的操作,但旋转了bitmap
-90度。
我的问题是,在我按下旋转buttons
约4-6次后,每张图片都会有所不同,无论如何,我都会收到错误:
`java.lang.NullPointerException`: Attempt to invoke virtual method 'int android.graphics.Bitmap.getWidth()' on a null object reference.
为什么在前几次旋转fxn正常工作时会发生此错误?我注意到,每次按下button
旋转时,位图的宽度和高度都会增加,但如果应用程序大于imageview
,则该应用程序不应该崩溃。我尝试了多种其他方法,但它们似乎崩溃或只是缩小图像。
这是我的代码:
rotateClockWise.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
Bitmap bitmap = imageViewtoBitmap(imageView);
int width = bitmap.getWidth();
Log.i(TAG, Integer.toString(width));
int height = bitmap.getHeight();
Log.i(TAG, Integer.toString(height));
Matrix matrix = new Matrix();
matrix.postRotate(90);
Bitmap rotatedBitmap = Bitmap.createBitmap(bitmap, 0, 0,
width, height, matrix, true );
imageView.setImageBitmap(rotatedBitmap);
}
});
rotateCCW.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
Bitmap bitmap = imageViewtoBitmap(imageView);
int width = bitmap.getWidth();
Log.i(TAG, Integer.toString(width));
int height = bitmap.getHeight();
Log.i(TAG, Integer.toString(height));
Matrix matrix = new Matrix();
matrix.postRotate(-90);
Bitmap rotatedBitmap = Bitmap.createBitmap(bitmap, 0, 0,
bitmap.getWidth(), bitmap.getHeight(), matrix, true );
imageView.setImageBitmap(rotatedBitmap);
}
});
public static Bitmap imageViewtoBitmap(ImageView imageView){
/**
* Args:
* imageview: an imageview
* Returns:
* the bitmap of the imageview
*/
//convert imageview to bitmap
imageView.setDrawingCacheEnabled(true);
// Without it the view will have a dimension of 0,0 and the bitmap will
be null
imageView.measure(View.MeasureSpec.makeMeasureSpec(0,
View.MeasureSpec.UNSPECIFIED),
View.MeasureSpec.makeMeasureSpec(0,
View.MeasureSpec.UNSPECIFIED));
// hardcoded so i always know how big image is
imageView.layout(0, 0, imageView.getMeasuredWidth(),
imageView.getMeasuredHeight());
if (imageView == null){
Log.i(TAG, "nothing");
}
imageView.buildDrawingCache(true);
Bitmap bitmapImage = Bitmap.createBitmap(imageView.getDrawingCache());
imageView.setDrawingCacheEnabled(false); // clear drawing cache
return bitmapImage;
}