transparency_ui/
transparency_ui.rs

1//! Demonstrates how to use transparency with UI.
2//! Shows two colored buttons with transparent text.
3
4use bevy::prelude::*;
5
6fn main() {
7    App::new()
8        .insert_resource(ClearColor(Color::BLACK))
9        .add_plugins(DefaultPlugins)
10        .add_systems(Startup, setup)
11        .run();
12}
13
14fn setup(mut commands: Commands, asset_server: Res<AssetServer>) {
15    commands.spawn(Camera2d);
16
17    let font_handle = asset_server.load("fonts/FiraSans-Bold.ttf");
18
19    commands
20        .spawn(Node {
21            width: percent(100),
22            height: percent(100),
23            align_items: AlignItems::Center,
24            justify_content: JustifyContent::SpaceAround,
25            ..default()
26        })
27        .with_children(|parent| {
28            parent
29                .spawn((
30                    Button,
31                    Node {
32                        width: px(150),
33                        height: px(65),
34                        justify_content: JustifyContent::Center,
35                        align_items: AlignItems::Center,
36                        ..default()
37                    },
38                    BackgroundColor(Color::srgb(0.1, 0.5, 0.1)),
39                ))
40                .with_children(|parent| {
41                    parent.spawn((
42                        Text::new("Button 1"),
43                        TextFont {
44                            font: font_handle.clone(),
45                            font_size: 33.0,
46                            ..default()
47                        },
48                        // Alpha channel of the color controls transparency.
49                        TextColor(Color::srgba(1.0, 1.0, 1.0, 0.2)),
50                    ));
51                });
52
53            // Button with a different color,
54            // to demonstrate the text looks different due to its transparency.
55            parent
56                .spawn((
57                    Button,
58                    Node {
59                        width: px(150),
60                        height: px(65),
61                        justify_content: JustifyContent::Center,
62                        align_items: AlignItems::Center,
63                        ..default()
64                    },
65                    BackgroundColor(Color::srgb(0.5, 0.1, 0.5)),
66                ))
67                .with_children(|parent| {
68                    parent.spawn((
69                        Text::new("Button 2"),
70                        TextFont {
71                            font: font_handle.clone(),
72                            font_size: 33.0,
73                            ..default()
74                        },
75                        // Alpha channel of the color controls transparency.
76                        TextColor(Color::srgba(1.0, 1.0, 1.0, 0.2)),
77                    ));
78                });
79        });
80}