public static File saveCanvasPictureToTempFile(Picture picture)
{
File tempFile = null;
// save to temporary file
File dir = getTempDir();
if(dir != null)
{
FileOutputStream fos = null;
try
{
File f = File.createTempFile("picture", ".stream", dir);
fos = new FileOutputStream(f);
picture.writeToStream(fos);
tempFile = f;
}
catch(IOException e)
{
Log.e(TAG, "failed to save picture", e);
}
finally
{
close(fos);
}
}
return tempFile;
}
此代碼應創建臨時文件並將其返回給主活動,但該文件在主活動中給我一個空指針異常。我可能做錯了什麼?打印圖像中的NUll指針異常
的代碼爲我的主要活動是
void printCanvasAsBitmapExample()
{
// create canvas to render on
Bitmap b = Bitmap.createBitmap(240, 240, Bitmap.Config.RGB_565);
Canvas c = new Canvas(b);
// fill background with WHITE
c.drawRGB(0xFF, 0xFF, 0xFF);
// draw text
Paint p = new Paint();
Typeface font = Typeface.create(Typeface.SANS_SERIF, Typeface.BOLD);
p.setTextSize(18);
p.setTypeface(font);
p.setAntiAlias(true);
Rect textBounds = new Rect();
p.getTextBounds(HELLO_WORLD, 0, HELLO_WORLD.length(), textBounds);
int x = (c.getWidth() - (textBounds.right-textBounds.left))/2;
int y = (c.getHeight() - (textBounds.bottom-textBounds.top))/2;
c.drawText(HELLO_WORLD, x, y, p);
// draw icon
Bitmap icon = BitmapFactory.decodeResource(getResources(), R.drawable.icon);
c.drawBitmap(icon, 0, 0, null);
// queue bitmap for printing
try
{
File f = PrintUtils.saveBitmapToTempFile(b, Bitmap.CompressFormat.PNG);
if(f != null)
{
PrintUtils.queueBitmapForPrinting(this, f, Bitmap.CompressFormat.PNG);
}
}
catch(Exception e)
{
Log.e(TAG, "failed to save/queue bitmap", e);
}
}
你可以把logcat錯誤在你的文章? – 2012-01-06 04:32:21
@Khush,發佈logcat錯誤或確切地提到你錯誤的位置 – 2012-01-06 05:12:37