2012-02-03 54 views
5

我試圖做出創建自定義卡的應用程序的自定義文本圖像。我想在自定義背景(JPG圖片)上添加一些文字。生成與Android的

是什麼做的最好的方法是什麼?我需要向用戶顯示該卡的預覽之前將其發送到服務器。

由於下面的代碼

+0

意味着你要在一個圖像文件添加文本:如果用戶已確認的圖像,那麼你可以通過下面的代碼把你的相對佈局的屏幕截圖? – 2012-02-03 07:09:08

+0

我有一個圖像(.JPG),並希望在頂部中心添加用戶的文本,並生成與文本的新JPG包含的 – Addev 2012-02-03 07:11:02

+0

檢查我的答案。 – 2012-02-03 07:36:42

回答

24

使用能達到您的要求

Bitmap src = BitmapFactory.decodeResource(getResources(), R.drawable.yourimage); // the original file yourimage.jpg i added in resources 
    Bitmap dest = Bitmap.createBitmap(src.getWidth(), src.getHeight(), Bitmap.Config.ARGB_8888); 

    String yourText = "My custom Text adding to Image"; 

    Canvas cs = new Canvas(dest); 
    Paint tPaint = new Paint(); 
    tPaint.setTextSize(35); 
    tPaint.setColor(Color.BLUE); 
    tPaint.setStyle(Style.FILL); 
    cs.drawBitmap(src, 0f, 0f, null); 
    float height = tPaint.measureText("yY"); 
    float width = tPaint.measureText(yourText); 
    float x_coord = (src.getWidth() - width)/2; 
    cs.drawText(yourText, x_coord, height+15f, tPaint); // 15f is to put space between top edge and the text, if you want to change it, you can 
    try { 
     dest.compress(Bitmap.CompressFormat.JPEG, 100, new FileOutputStream(new File("/sdcard/ImageAfterAddingText.jpg"))); 
     // dest is Bitmap, if you want to preview the final image, you can display it on screen also before saving 
    } catch (FileNotFoundException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 

您在清單文件中使用下面的權限。

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> 

對於我的設備的路徑是/sdcard訪問外部SD卡,也可以用於其他設備而異。有些設備可能有/mnt/sdcard可能是內部的SD卡。在使用此代碼之前,請檢查它。

其實我爲上面的代碼寫了一些其他的問題,從照相機捕獲後需要時間戳在照片上。我爲您提供了相同的解決方案,並針對您的具體要求做了一些修改。

我希望你能理解這一點。如果您對代碼有任何疑問,請隨時提問。

+0

真的很好...謝謝... – Aravin 2013-10-22 15:33:55

+0

如何使用拖放方式移動圖像上添加的文本。 – Mayur 2014-05-14 04:01:28

+0

可以相同,而不將圖像保存到外部存儲,只是發送到服務器可以實現嗎? – user3677331 2015-06-26 09:35:42

4

我不確定這是最好的解決方案,但它可以幫助你。

第1步:創建一個相對佈局(任何其他),並將您的圖像設置爲其背景。

第2步:現在添加一個寬度和高度的textview作爲fill_parent或match_parent以及重力作爲top | center_horizo​​ntal。

第3步:現在添加另一個按鈕或任何其他佈局控件,將觸發用戶確認。 (您應該將此控件放置在相對佈局外)。

第四步:

v1.setDrawingCacheEnabled(true);//v1 is the object of your Relative layout 
      Bitmap bm = v1.getDrawingCache(); 
      if (bm != null) { 

       //TODO:write the code for saving the image. 

       Toast toast = Toast.makeText(YourActivity.this, "image saved", 
         Toast.LENGTH_LONG); 
       toast.show(); 
      } else { 
       Toast toast = Toast.makeText(YourActivity.this, 
         "No image saved.", Toast.LENGTH_LONG); 
       toast.show(); 
      }