如何在Canvas上水平居中文本

问题描述 投票:1回答:1

我有一个带有2个TextView的ImageView。我试图将字幕与Canvas的中位数(宽度/ 2)对齐。以下是我想要实现的目标:

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();
        }

        Uri contentUri = Uri.fromFile(file);
        mediaScanIntent.setData(contentUri);
        Objects.requireNonNull(getContext()).sendBroadcast(mediaScanIntent);
        counter++;
    }
java android android-canvas textview android-paint
1个回答
2
投票

它其实很简单。您需要做的就是使用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

© www.soinside.com 2019 - 2024. All rights reserved.