【发布时间】:2017-08-07 04:29:29
【问题描述】:
在我的应用程序中,我有它,以便每次按下 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;
}
【问题讨论】:
-
你能发布整个异常堆栈吗
标签: java android bitmap nullpointerexception rotation