Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add control of line height and letter spacing #3302

Merged
merged 8 commits into from
Sep 5, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 9 additions & 7 deletions crates/egui/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -92,14 +92,16 @@
//! # });
//! ```
//!
//! ## Conventions
//! ## Coordinate system
//! The left-top corner of the screen is `(0.0, 0.0)`,
//! with X increasing to the right and Y increasing downwards.
//!
//! Conventions unless otherwise specified:
//! `egui` uses logical _points_ as its coordinate system.
//! Those related to physical _pixels_ by the `pixels_per_point` scale factor.
//! For example, a high-dpi screeen can have `pixels_per_point = 2.0`,
//! meaning there are two physical screen pixels for each logical point.
//!
//! * angles are in radians
//! * `Vec2::X` is right and `Vec2::Y` is down.
//! * `Pos2::ZERO` is left top.
//! * Positions and sizes are measured in _points_. Each point may consist of many physical pixels.
//! Angles are in radians, and are measured clockwise from the X-axis, which has angle=0.
//!
//! # Integrating with egui
//!
Expand Down Expand Up @@ -352,7 +354,7 @@ pub mod text {
pub use crate::text_edit::CCursorRange;
pub use epaint::text::{
cursor::CCursor, FontData, FontDefinitions, FontFamily, Fonts, Galley, LayoutJob,
LayoutSection, TextFormat, TAB_SIZE,
LayoutSection, TextFormat, TextWrapping, TAB_SIZE,
};
}

Expand Down
35 changes: 33 additions & 2 deletions crates/egui/src/widget_text.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
use std::borrow::Cow;
use std::sync::Arc;
use std::{borrow::Cow, sync::Arc};

use crate::{
style::WidgetVisuals, text::LayoutJob, Align, Color32, FontFamily, FontSelection, Galley, Pos2,
Expand All @@ -25,6 +24,8 @@ use crate::{
pub struct RichText {
text: String,
size: Option<f32>,
extra_letter_spacing: f32,
line_height: Option<f32>,
family: Option<FontFamily>,
text_style: Option<TextStyle>,
background_color: Color32,
Expand Down Expand Up @@ -100,6 +101,32 @@ impl RichText {
self
}

/// Extra spacing between letters, in points.
///
/// Default: 0.0.
///
/// For even text it is recommended you round this to an even number of _pixels_,
/// e.g. using [`crate::Painter::round_to_pixel`].
#[inline]
pub fn extra_letter_spacing(mut self, extra_letter_spacing: f32) -> Self {
self.extra_letter_spacing = extra_letter_spacing;
self
}

/// Explicit line height of the text in points.
///
/// This is the distance between the bottom row of two subsequent lines of text.
///
/// If `None` (the default), the line height is determined by the font.
///
/// For even text it is recommended you round this to an even number of _pixels_,
/// e.g. using [`crate::Painter::round_to_pixel`].
#[inline]
pub fn line_height(mut self, line_height: Option<f32>) -> Self {
self.line_height = line_height;
self
}

/// Select the font family.
///
/// This overrides the value from [`Self::text_style`].
Expand Down Expand Up @@ -253,6 +280,8 @@ impl RichText {
let Self {
text,
size,
extra_letter_spacing,
line_height,
family,
text_style,
background_color,
Expand Down Expand Up @@ -309,6 +338,8 @@ impl RichText {

let text_format = crate::text::TextFormat {
font_id,
extra_letter_spacing,
line_height,
color: text_color,
background: background_color,
italics,
Expand Down
3 changes: 2 additions & 1 deletion crates/egui_demo_lib/src/demo/demo_app_windows.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,8 @@ impl Default for Demos {
Box::<super::sliders::Sliders>::default(),
Box::<super::strip_demo::StripDemo>::default(),
Box::<super::table_demo::TableDemo>::default(),
Box::<super::text_edit::TextEdit>::default(),
Box::<super::text_edit::TextEditDemo>::default(),
Box::<super::text_layout::TextLayoutDemo>::default(),
Box::<super::widget_gallery::WidgetGallery>::default(),
Box::<super::window_options::WindowOptions>::default(),
Box::<super::tests::WindowResizeTest>::default(),
Expand Down
68 changes: 1 addition & 67 deletions crates/egui_demo_lib/src/demo/misc_demo_window.rs
Original file line number Diff line number Diff line change
@@ -1,14 +1,12 @@
use super::*;
use egui::{epaint::text::TextWrapping, *};
use egui::*;

/// Showcase some ui code
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
#[cfg_attr(feature = "serde", serde(default))]
pub struct MiscDemoWindow {
num_columns: usize,

text_break: TextBreakDemo,

widgets: Widgets,
colors: ColorWidgets,
custom_collapsing_header: CustomCollapsingHeader,
Expand All @@ -24,8 +22,6 @@ impl Default for MiscDemoWindow {
MiscDemoWindow {
num_columns: 2,

text_break: Default::default(),

widgets: Default::default(),
colors: Default::default(),
custom_collapsing_header: Default::default(),
Expand Down Expand Up @@ -72,8 +68,6 @@ impl View for MiscDemoWindow {
.default_open(false)
.show(ui, |ui| {
text_layout_demo(ui);
ui.separator();
self.text_break.ui(ui);
ui.vertical_centered(|ui| {
ui.add(crate::egui_github_link_file_line!());
});
Expand Down Expand Up @@ -644,63 +638,3 @@ fn text_layout_demo(ui: &mut Ui) {

ui.label(job);
}

#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
#[cfg_attr(feature = "serde", serde(default))]
struct TextBreakDemo {
break_anywhere: bool,
max_rows: usize,
overflow_character: Option<char>,
}

impl Default for TextBreakDemo {
fn default() -> Self {
Self {
max_rows: 1,
break_anywhere: true,
overflow_character: Some('…'),
}
}
}

impl TextBreakDemo {
pub fn ui(&mut self, ui: &mut Ui) {
let Self {
break_anywhere,
max_rows,
overflow_character,
} = self;

use egui::text::LayoutJob;

ui.horizontal(|ui| {
ui.add(DragValue::new(max_rows));
ui.label("Max rows");
});

ui.horizontal(|ui| {
ui.label("Line-break:");
ui.radio_value(break_anywhere, false, "word boundaries");
ui.radio_value(break_anywhere, true, "anywhere");
});

ui.horizontal(|ui| {
ui.selectable_value(overflow_character, None, "None");
ui.selectable_value(overflow_character, Some('…'), "…");
ui.selectable_value(overflow_character, Some('—'), "—");
ui.selectable_value(overflow_character, Some('-'), " - ");
ui.label("Overflow character");
});

let mut job =
LayoutJob::single_section(crate::LOREM_IPSUM_LONG.to_owned(), TextFormat::default());
job.wrap = TextWrapping {
max_rows: *max_rows,
break_anywhere: *break_anywhere,
overflow_character: *overflow_character,
..Default::default()
};

ui.label(job); // `Label` overrides some of the wrapping settings, e.g. wrap width
}
}
1 change: 1 addition & 0 deletions crates/egui_demo_lib/src/demo/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ pub mod strip_demo;
pub mod table_demo;
pub mod tests;
pub mod text_edit;
pub mod text_layout;
pub mod toggle_switch;
pub mod widget_gallery;
pub mod window_options;
Expand Down
10 changes: 5 additions & 5 deletions crates/egui_demo_lib/src/demo/text_edit.rs
Original file line number Diff line number Diff line change
@@ -1,20 +1,20 @@
/// Showcase [`TextEdit`].
/// Showcase [`egui::TextEdit`].
#[derive(PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
#[cfg_attr(feature = "serde", serde(default))]
pub struct TextEdit {
pub struct TextEditDemo {
pub text: String,
}

impl Default for TextEdit {
impl Default for TextEditDemo {
fn default() -> Self {
Self {
text: "Edit this text".to_owned(),
}
}
}

impl super::Demo for TextEdit {
impl super::Demo for TextEditDemo {
fn name(&self) -> &'static str {
"🖹 TextEdit"
}
Expand All @@ -30,7 +30,7 @@ impl super::Demo for TextEdit {
}
}

impl super::View for TextEdit {
impl super::View for TextEditDemo {
fn ui(&mut self, ui: &mut egui::Ui) {
let Self { text } = self;

Expand Down
135 changes: 135 additions & 0 deletions crates/egui_demo_lib/src/demo/text_layout.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,135 @@
/// Showcase text layout
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
#[cfg_attr(feature = "serde", serde(default))]
pub struct TextLayoutDemo {
break_anywhere: bool,
max_rows: usize,
overflow_character: Option<char>,
extra_letter_spacing_pixels: i32,
line_height_pixels: u32,
}

impl Default for TextLayoutDemo {
fn default() -> Self {
Self {
max_rows: 3,
break_anywhere: true,
overflow_character: Some('…'),
extra_letter_spacing_pixels: 0,
line_height_pixels: 0,
}
}
}

impl super::Demo for TextLayoutDemo {
fn name(&self) -> &'static str {
"🖹 Text Layout"
}

fn show(&mut self, ctx: &egui::Context, open: &mut bool) {
egui::Window::new(self.name())
.open(open)
.resizable(true)
.show(ctx, |ui| {
use super::View as _;
self.ui(ui);
});
}
}

impl super::View for TextLayoutDemo {
fn ui(&mut self, ui: &mut egui::Ui) {
let Self {
break_anywhere,
max_rows,
overflow_character,
extra_letter_spacing_pixels,
line_height_pixels,
} = self;

use egui::text::LayoutJob;

let pixels_per_point = ui.ctx().pixels_per_point();
let points_per_pixel = 1.0 / pixels_per_point;

ui.vertical_centered(|ui| {
ui.add(crate::egui_github_link_file_line!());
});

ui.add_space(12.0);

egui::Grid::new("TextLayoutDemo")
.num_columns(2)
.show(ui, |ui| {
ui.label("Max rows:");
ui.add(egui::DragValue::new(max_rows));
ui.end_row();

ui.label("Line-break:");
ui.horizontal(|ui| {
ui.radio_value(break_anywhere, false, "word boundaries");
ui.radio_value(break_anywhere, true, "anywhere");
});
ui.end_row();

ui.label("Overflow character:");
ui.horizontal(|ui| {
ui.selectable_value(overflow_character, None, "None");
ui.selectable_value(overflow_character, Some('…'), "…");
ui.selectable_value(overflow_character, Some('—'), "—");
ui.selectable_value(overflow_character, Some('-'), " - ");
});
ui.end_row();

ui.label("Extra letter spacing:");
ui.add(egui::DragValue::new(extra_letter_spacing_pixels).suffix(" pixels"));
ui.end_row();

ui.label("Line height:");
ui.horizontal(|ui| {
if ui
.selectable_label(*line_height_pixels == 0, "Default")
.clicked()
{
*line_height_pixels = 0;
}
if ui
.selectable_label(*line_height_pixels != 0, "Custom")
.clicked()
{
*line_height_pixels = (pixels_per_point * 20.0).round() as _;
}
if *line_height_pixels != 0 {
ui.add(egui::DragValue::new(line_height_pixels).suffix(" pixels"));
}
});
ui.end_row();
});

ui.add_space(12.0);

egui::ScrollArea::vertical().show(ui, |ui| {
let extra_letter_spacing = points_per_pixel * *extra_letter_spacing_pixels as f32;
let line_height =
(*line_height_pixels != 0).then_some(points_per_pixel * *line_height_pixels as f32);

let mut job = LayoutJob::single_section(
crate::LOREM_IPSUM_LONG.to_owned(),
egui::TextFormat {
extra_letter_spacing,
line_height,
..Default::default()
},
);
job.wrap = egui::text::TextWrapping {
max_rows: *max_rows,
break_anywhere: *break_anywhere,
overflow_character: *overflow_character,
..Default::default()
};

// NOTE: `Label` overrides some of the wrapping settings, e.g. wrap width
ui.label(job);
});
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -188,5 +188,6 @@ fn format_from_style(
underline,
strikethrough,
valign,
..Default::default()
}
}
Loading
Loading