亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在畫布上水平居中文本

如何在畫布上水平居中文本

慕哥9229398 2022-07-20 15:43:09
我有一個帶有 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


查看完整回答
反對 回復 2022-07-20
  • 1 回答
  • 0 關注
  • 148 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號