我有一個帶有 2 個 TextViews 的 ImageView。我正在嘗試將字幕的中位數與Canvas. 這是我要實現的目標的說明:https://imgur.com/a/7fklSBv到目前為止,我的嘗試將 TextView 從其左端與 Canvas 的垂直中心對齊。public void createBitmapAndSave(ImageView img) { BitmapDrawable bitmapDrawable = ((BitmapDrawable) img.getDrawable()); Bitmap bitmap = bitmapDrawable.getBitmap(); Bitmap mutableBitmap = bitmap.copy(Bitmap.Config.ARGB_8888, true); String topText = topTextView.getText().toString(); String bottomText = bottomTextView.getText().toString(); Canvas canvas = new Canvas(mutableBitmap); Paint topPaint = new Paint(); Paint bottomPaint = new Paint(); topPaint.setColor(Color.BLUE); topPaint.setStyle(Paint.Style.FILL); topPaint.setShadowLayer(10f, 10f, 10f, Color.BLACK); topPaint.setTextSize(topTextView.getTextSize()); bottomPaint.setColor(Color.RED); bottomPaint.setStyle(Paint.Style.FILL); bottomPaint.setShadowLayer(10f, 10f, 10f, Color.BLACK); bottomPaint.setTextSize(bottomTextView.getTextSize()); canvas.drawText(topText, (canvas.getWidth()) / 2, 200, topPaint); canvas.drawText(bottomText, (canvas.getWidth()) / 2, canvas.getHeight() - 200, bottomPaint); 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); mutableBitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream); stream.flush(); stream.close(); Toast.makeText(getContext(), "Meme Saved", Toast.LENGTH_SHORT).show(); } catch (IOException e) { e.printStackTrace(); } }
1 回答

料青山看我應如是
TA貢獻1772條經驗 獲得超8個贊
其實很簡單。您需要做的就是使用該Paint.measureText()方法獲取文本的寬度,除以 2 得到一半,然后將其向左移動以使其居中。
看看這個。我創建了兩個float變量來保存 Canvas 上每個文本的寬度:
float topTextMeasurement = topPaint.measureText(topText);
float bottomTextMeasurement = bottomPaint.measureText(bottomText);
然后我在您的Canvas.drawText()方法的 x 參數中進行了上述調整。
canvas.drawText(topText, topX - (topTextMeasurement/2), 200, topPaint);
canvas.drawText(bottomText, bottomX - (bottomTextMeasurement/2), canvas.getHeight() - 200, bottomPaint);
但這僅適用于您的文本不超過一行的情況。對于多行文本,我建議您查看DynamicLayout
添加回答
舉報
0/150
提交
取消