nativescript-bitmap-factory icon indicating copy to clipboard operation
nativescript-bitmap-factory copied to clipboard

How To Center Text

Open asiedusamuel opened this issue 5 years ago • 1 comments

Is there a way to center text horizontally and vertically?

asiedusamuel avatar Aug 23 '19 23:08 asiedusamuel

As far as I can see, there is no such method. However, as a workaround, you can use Label to determine your text width and height (without rendering it) and then use these values for tweaking your left, top coordinates

const label = new Label();
label.text = text; // Assigning your text to the label
label.fontSize = fontSize; // Assigning your font size

(<any>label)._setupAsRootView(view._context); // `view` is any instance of View class from your page.
label.onLoaded();
label.measure(0, 0);

const width = toDeviceIndependentPixels(label.getMeasuredWidth()); // Here you get actual width of the label with your text

Now you can calculate the left offset for example and use it to position your text, like

const offset = (yourImageWidth - width) / 2;

bmp.dispose(() => {
    bmp.writeText(text, `${offset},4`, {
        color: '#FFFFFF',
        size: fontSize,
});

The same can be used for the height. Hope, this helps

SergeyMell avatar Oct 11 '20 13:10 SergeyMell