2011-08-25 31 views
0

我有個問題要問。我只想在下面的代碼中將文本添加到位圖中。當我調試到Bitmap bmp = bmp1.copy(bmp1.getConfig(), true);在監視窗口中一切工作正常,我可以看到640和480的寬度和高度。複製位圖問題

但執行復制方法後,它返回到bmp的位圖,但bmp的寬度和高度是-1和-1,並且它不能添加文本。有些人會告訴我爲什麼以及如何解決這個問題。非常感謝

String strPath=Environment.getExternalStorageDirectory().toString(); 
    String strFileNameIn="aaa.jpg"; 
    File inFile=new File(strPath+File.separator+strFileNameIn); 
    try { 
     if (inFile.exists()) { 
    FileInputStream inStream = new FileInputStream(inFile); 
    BitmapDrawable bmpDraw = new BitmapDrawable(inStream); 
     Bitmap bmp1 = bmpDraw.getBitmap(); 
    Bitmap bmp = bmp1.copy(bmp1.getConfig(), true); 

    Canvas cv = new Canvas(bmp); 
    SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
    String strText = sDateFormat.format(new Date()); 
     Paint p = new Paint(); 
    p.setColor(Color.RED); 

    cv.drawText(strText, 0, 0, p); 
    cv.save(Canvas.ALL_SAVE_FLAG); 
    cv.restore(); 
    } 
     } catch (Exception e) { 
      String strMsg = e.getMessage(); 
     } 

回答

0

您可以通過bitmapfactory更容易地獲得位圖。

如何:

Bitmap bitmap = BitmapFactory.decodeFile("your file"); 
if (bitmap != null) { 
    Paint p = new Paint(); 
    Canvas cv = new Canvas(); 
    cv.drawBitmap(bitmap, 0, 0, p); 
    SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
    String strText = sDateFormat.format(new Date()); 
    p.setColor(Color.RED); 

    cv.drawText(strText, 0, 0, p); 
    cv.save(Canvas.ALL_SAVE_FLAG); 
    cv.restore(); 
} 
+0

喜塔馬斯。感謝您的回覆。我厭倦了你的建議,decodeFile方法返回Bitmap對象,但它符合我前面描述的寬度和高度-1,-1的問題。這是我的形象問題嗎?但我可以正確地查看它。上帝......有什麼建議嗎? – jinmengcheng

+0

大家好。感謝您查看我的線索。我終於找出問題了。實際上所有的東西都運行良好,並且文字被繪製在照片上,但是我看不到,因爲我將起始位置(0,0)設置爲文本的左下角(或文本矩形),它剛剛出現當前圖像的邊界。 – jinmengcheng