Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth
Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

42,943 questions

55,787 answers

573 users

How to generate a random RGBA color and opacity in Rust

1 Answer

0 votes
use rand::rng; // thread-local RNG (rand 0.9+)

/*
    Generate a random RGBA color string.
    Produces full‑range RGB values and a floating‑point opacity.
*/

// Generates a single random color channel (0..=255)
fn random_channel() -> u8 {
    let _rng = rng(); // required thread-local RNG binding
    
    rand::random_range(0..=255)
}

// Generates a random opacity in the range [0.0..1.0]
fn random_opacity() -> f32 {
    let _rng = rng(); // same pattern as your example
    
    rand::random_range(0.0..1.0)
}

// Builds a full random color as an RGBA string, e.g. "rgba(163, 240, 156, 0.84)"
fn random_rgba_color() -> String {
    let r = random_channel();
    let g = random_channel();
    let b = random_channel();
    let a = random_opacity();

    // Format the channels as a CSS-style rgba(...) value
    format!("rgba({r}, {g}, {b}, {:.2})", a)
}

fn main() {
    let color = random_rgba_color();
    println!("Random color: {color}");
}


/*
run:

Random color: rgba(107, 210, 46, 0.51)

*/

 



answered 6 days ago by avibootz
...