Add ui.code(text): like ui.monospace() but also adds a background

This commit is contained in:
Emil Ernerfeldt 2021-01-26 22:05:14 +01:00
parent eedb63bb3b
commit 7d8ebb4c8f
2 changed files with 29 additions and 0 deletions

View file

@ -643,6 +643,13 @@ impl Ui {
self.add(label.into().monospace()) self.add(label.into().monospace())
} }
/// Show text as monospace with a gray background.
///
/// Shortcut for `add(Label::new(text).code())`
pub fn code(&mut self, label: impl Into<Label>) -> Response {
self.add(label.into().code())
}
/// Shortcut for `add(Label::new(text).small())` /// Shortcut for `add(Label::new(text).small())`
pub fn small(&mut self, label: impl Into<Label>) -> Response { pub fn small(&mut self, label: impl Into<Label>) -> Response {
self.add(label.into().small()) self.add(label.into().small())

View file

@ -7,6 +7,7 @@ pub struct Label {
pub(crate) text: String, pub(crate) text: String,
pub(crate) multiline: Option<bool>, pub(crate) multiline: Option<bool>,
pub(crate) text_style: Option<TextStyle>, pub(crate) text_style: Option<TextStyle>,
pub(crate) background_color: Color32,
pub(crate) text_color: Option<Color32>, pub(crate) text_color: Option<Color32>,
} }
@ -16,6 +17,7 @@ impl Label {
text: text.into(), text: text.into(),
multiline: None, multiline: None,
text_style: None, text_style: None,
background_color: Color32::TRANSPARENT,
text_color: None, text_color: None,
} }
} }
@ -49,10 +51,22 @@ impl Label {
self.text_style(TextStyle::Monospace) self.text_style(TextStyle::Monospace)
} }
/// Monospace label with gray background
pub fn code(self) -> Self {
self.text_style(TextStyle::Monospace)
.background_color(Color32::from_gray(64)) // TODO: style
}
pub fn small(self) -> Self { pub fn small(self) -> Self {
self.text_style(TextStyle::Small) self.text_style(TextStyle::Small)
} }
/// Fill-color behind the text
pub fn background_color(mut self, background_color: impl Into<Color32>) -> Self {
self.background_color = background_color.into();
self
}
pub fn text_color(mut self, text_color: impl Into<Color32>) -> Self { pub fn text_color(mut self, text_color: impl Into<Color32>) -> Self {
self.text_color = Some(text_color.into()); self.text_color = Some(text_color.into());
self self
@ -87,6 +101,14 @@ impl Label {
// This should be the easiest method of putting text anywhere. // This should be the easiest method of putting text anywhere.
pub fn paint_galley(&self, ui: &mut Ui, pos: Pos2, galley: Galley) { pub fn paint_galley(&self, ui: &mut Ui, pos: Pos2, galley: Galley) {
if self.background_color != Color32::TRANSPARENT {
for row in &galley.rows {
let rect = row.rect().translate(pos.to_vec2());
let rect = rect.expand(1.0); // looks better
ui.painter().rect_filled(rect, 0.0, self.background_color);
}
}
let text_style = self.text_style_or_default(ui.style()); let text_style = self.text_style_or_default(ui.style());
let text_color = self let text_color = self
.text_color .text_color