我正在嘗試從用戶那里獲取文本輸入并將其繪制在圖像上,Canvas但圖像被保存而沒有應該繪制的內容?,F在,我只是想在擔心字體、顏色、樣式等之前獲取圖像上的文本。這是我的代碼: public void createBitmapAndSave(ImageView img){ BitmapDrawable bitmapDrawable = ((BitmapDrawable) img.getDrawable()); Bitmap bitmap = bitmapDrawable.getBitmap(); Bitmap mutableBitmap = bitmap.copy(Bitmap.Config.ARGB_8888, true); Canvas canvas = new Canvas(mutableBitmap); Paint paint = new Paint(); paint.setColor(Color.BLUE); paint.setTextSize(200); paint.setStyle(Paint.Style.FILL); paint.setShadowLayer(10f, 10f, 10f, Color.BLACK); String topText = topTextView.getText().toString(); String bottomText = bottomTextView.getText().toString(); canvas.drawText(topText, 0, 0, paint); canvas.drawText(bottomText, 50, 50, paint); File file; Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE); String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).getPath(); file = new File(path + "/SimpliMeme/" + timeStamp + "-" + counter + ".jpg"); file.getParentFile().mkdir(); try{ OutputStream stream = new FileOutputStream(file); bitmap.compress(Bitmap.CompressFormat.JPEG,100,stream); stream.flush(); stream.close(); Toast.makeText(getContext(), "Meme Saved", Toast.LENGTH_SHORT).show(); } catch (IOException e){ e.printStackTrace();} Uri contentUri = Uri.fromFile(file); mediaScanIntent.setData(contentUri); Objects.requireNonNull(getContext()).sendBroadcast(mediaScanIntent); counter++; }目前,.drawText()基于我在其他 SO 帖子中看到的示例,我只有 2 個實現。我的假設是文本不可見,并且沒有對圖像進行任何更改,因為我沒有為paint對象提供任何屬性。
1 回答
躍然一笑
TA貢獻1826條經驗 獲得超6個贊
您看不到任何更改的主要問題是您進行了更改mutableBitmap但將原始文件保存bitmap到磁盤。
這可以通過將前兩個(甚至三個)語句連接在一起來避免:
final Bitmap bitmap = bitmapDrawable.getBitmap() .copy(Bitmap.Config.ARGB_8888, true);
您在其他任何地方都不需要原始位圖,這有效地防止了您犯錯。不要做你不需要做的事情。
一些技巧:
繪圖時始終明確。指定顏色,指定字體。您不能信任默認值。(至少我不確定這些值。默認顏色是黑色還是透明?)
如果您想完全確定字體,請將其與您的應用程序捆綁在一起或使用可下載的字體。一些平臺允許用戶將默認字體更改為瘋狂的東西。
如果您想繪制多行文本,請查看
StaticLayout.確保您的應用可在 Android 7 及更高版本上運行。禁止在您的應用之外發送帶有文件 Uri 的意圖。
添加回答
舉報
0/150
提交
取消
