nativescript-bitmap-factory
nativescript-bitmap-factory copied to clipboard
How To Center Text
Is there a way to center text horizontally and vertically?
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