javaandroidandroid-canvastextviewandroid-paint

How to center text horizontally on Canvas


I have an ImageView with 2 TextViews. I am trying to align the captions by its median with the median (width/2) of the Canvas. Here is an illustration of what I'm trying to achieve:

https://i.sstatic.net/R5AmI.jpg

So far, my attempt aligns the TextView from its left-end with the vertical-centre of the 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++;
    }

Solution

  • Its actually simple. All you need to do is to use the Paint.measureText() method to get the width of the text, divide by 2 to get its half and then shift it to the left to center it.

    Take a look at this. I've created two float variables that hold the width of each text on Canvas:

    float topTextMeasurement = topPaint.measureText(topText);
    float bottomTextMeasurement = bottomPaint.measureText(bottomText);
    

    Then I've done the above adjustment in your Canvas.drawText() methods' x parameters.

    canvas.drawText(topText, topX - (topTextMeasurement/2), 200, topPaint);
    canvas.drawText(bottomText, bottomX - (bottomTextMeasurement/2), canvas.getHeight() - 200, bottomPaint);
    

    But this is only if your text is not going to exceed a single line. For multi-line texts, I suggest that you look into DynamicLayout