How to centre text?

I’m building a widget and I want the text to be centered - best described in the following image:

On the left is what I have managed so far, and on the right is the text-centering behaviour that I am after.

When creating the iced::advanced::text::Text in my widget, I can set align_x to Alignment::Center (and that is the option I’m using in the screenshot here), however, that only seems to change the attachment point of the text when I continue on to draw it using renderer::fill_text.

How can I get all of the lines of the text to be centered?

Update your app to use the master version of iced instead of 0.13 and you will get the behavior you were expecting. It’s a new feature.

To use master, change your Cargo.toml to point to GitHub:

iced = { git = "https://github.com/iced-rs/iced.git", branch = "master" }

You can also pin it to a specific commit by specifying the rev key. See the Cargo docs for this and more details which are out of scope for this question.

If you have any dependencies that depend on iced, you will have to check if they provide a version that is compatible with 0.14.0-dev which is the current, in-progress version at master. If they don’t, you’ll have to drop those dependencies or fork-and-update them yourself.

We don’t know when the next iced release will be. There are no deadlines. I’m guessing mid-to-late Summer at this point (northern hemisphere).

Sorry, I mentioned it in my other thread, but not this one: I am using the latest master branch.

Here is how I am instantiating the text in Widget::draw:

let text = iced::advanced::Text {
    content: tab_label,
    bounds: Size::new(
        tab_bounds.width - self.padding.horizontal(),
        tab_bounds.height,
    ),
    size: self.font_size.into(),
    line_height: Default::default(),
    font: renderer.default_font(),
    align_x: iced::advanced::text::Alignment::Center,
    align_y: alignment::Vertical::Center,
    shaping: text::Shaping::Basic,
    wrapping: text::Wrapping::Word,
};

renderer.fill_text(text, tab_bounds.center(), style.text_color, tab_bounds);

I think the only way to center text is to use the Paragraph API like the text widget does. Paragraphs should be laid out during fn layout and held in your state, only to be drawn during fn draw. You can see how text does that.

I had an editable textbox widget laying around so I decided to put it up on GitHub in case helpful. It’s here: GitHub - airstrike/texty: throwaway iced textbox widget

Thank you for the reference - I’ll use the Paragraph API for drawing. I’m actually using it already in Widget::layout to layout some labels relative to each other, before just discarding it…!

EDIT: problem solved by using the Paragraph API as suggested, thanks @airstrike!

image

1 Like