user3794400
user3794400

Reputation: 21

Centering Text on Android Canvas Including Accurate Bounds

Here is the situation. I am rendering to a canvas. Nothing else is being rendered, the canvas is effectively fullscreen. There is only one view.

I want to make a simple (text) button. This consists of two parts: visually drawing it, and checking bounds to see if it is pressed. These two things should be consistent.

Ideally the centering is optional, though I would expect switching it to be simple.

After far too many hours, I suspect it is not simply an alignment issue, but also a use of the API that is the source of the problem.

How can this be done?

Upvotes: 0

Views: 622

Answers (1)

Jayadev
Jayadev

Reputation: 201

Just use static layouts and then you can keep the text center aligned inside the canvas even if the size is increased by some limit by auto aligning the text.

        Rect bounds = new Rect(x1, y1, x2, y2);// set the bounds
        String textOnCanvas = "text to be wriiten";
        StaticLayout sl = new StaticLayout(textOnCanvas, textPaint,
                bounds.width(), Layout.Alignment.ALIGN_CENTER, 1, 1, true);
        canvas.save();
        float textHeight = getTextHeight(textOnCanvas, textPaint);
        int numberOfTextLines = sl.getLineCount();
        float textYCoordinate = bounds.exactCenterY() -
                ((numberOfTextLines * textHeight) / 2);

        //text will be drawn from left
        float textXCoordinate = bounds.left;
        canvas.translate(textXCoordinate, textYCoordinate);
        //draws static layout on canvas
        sl.draw(canvas);
        canvas.restore();

The parameter Layout.Alignment.ALIGN_CENTER of static layout will take care of the center alignment of the text in canvas.

Upvotes: 1

Related Questions