Flutter: How can I make a Random color generator Background
You can use Random
class to do that:
But if you want to change the color when button is pressed, you have to use a StatefulWidget
. A simple example is like below:
import 'package:flutter/material.dart';
import 'dart:math';
void main() {
runApp(
MaterialApp(
home: MyApp(),
),
);
}
class MyApp extends StatefulWidget {
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
List colors = [Colors.red, Colors.green, Colors.yellow];
Random random = new Random();
int index = 0;
void changeIndex() {
setState(() => index = random.nextInt(3));
}
@override
Widget build(BuildContext context) {
return Center(
child: RaisedButton(
onPressed: () => changeIndex(),
child: Text('Click'),
color: colors[index],
),
);
}
}
Also, there is a package called random_pk by pawankumar, that will give us random color each and every time your app's build method get called.
Random color generator
Use getRandomColor()
in place of "#0000FF"
:
function getRandomColor() {
var letters = '0123456789ABCDEF';
var color = '#';
for (var i = 0; i < 6; i++) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}
function setRandomColor() {
$("#colorpad").css("background-color", getRandomColor());
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="colorpad" style="width:300px;height:300px;background-color:#000">
</div>
<button onclick="setRandomColor()">Random Color</button>
Get Random Color
Here's the answer I started posting before you deleted and then un-deleted your question:
public partial class Form1 : Form
{
private Random rnd = new Random();
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Color randomColor = Color.FromArgb(rnd.Next(256), rnd.Next(256), rnd.Next(256));
BackColor = randomColor;
}
}
Random Color Generator and how to apply it to my existing Gradient
- convert to hex
- do not reuse the color1/color2 variables
- set the color before converting
Note: You many want to loop the second color in case you get the same value
const rgbToHex = rgb => '#' + (rgb.match(/[0-9|.]+/g).map((x, i) => i === 3 ? parseInt(255 * parseFloat(x)).toString(16) : parseInt(x).toString(16)).join('')).padStart(2, '0').toUpperCase();
var css = document.querySelector("h3");
var color1 = document.querySelector(".color1");
var color2 = document.querySelector(".color2");
var body = document.getElementById("gradient");
var button1 = document.querySelector(".button1");
function setGradient() {
body.style.background =
"linear-gradient(to right, " +
color1.value +
", " +
color2.value +
")";
css.textContent = body.style.background + ";";
}
function randomColorGenerator() {
var col1 = "rgb" + "(" + (Math.floor(Math.random() * 255) +
", " +
Math.floor(Math.random() * 255) +
", " +
Math.floor(Math.random() * 255) +
")" + ";");
var col2 = "rgb" + "(" + (Math.floor(Math.random() * 255) +
", " +
Math.floor(Math.random() * 255) +
", " +
Math.floor(Math.random() * 255) +
")" + ";");
console.log(col1)
color1.value=rgbToHex(col1)
color2.value=rgbToHex(col2)
console.log(color1.value,color2.value)
setGradient()
}
color1.addEventListener("input", setGradient);
color2.addEventListener("input", setGradient);
button1.addEventListener("click", randomColorGenerator);
<body id="gradient" onload="setGradient()">
<h1>Background Generator</h1>
<input class="color1" type="color" name="color1" value="#00ff00">
<input class="color2" type="color" name="color2" value="#ff0000">
<h2>Current CSS Background</h2>
<button class='button1'>Random Color</button>
<h3></h3>
<script type="text/javascript" src="script.js"></script>
</body>
Creating random colour in Java?
Use the random library:
import java.util.Random;
Then create a random generator:
Random rand = new Random();
As colours are separated into red green and blue, you can create a new random colour by creating random primary colours:
// Java 'Color' class takes 3 floats, from 0 to 1.
float r = rand.nextFloat();
float g = rand.nextFloat();
float b = rand.nextFloat();
Then to finally create the colour, pass the primary colours into the constructor:
Color randomColor = new Color(r, g, b);
You can also create different random effects using this method, such as creating random colours with more emphasis on certain colours ... pass in less green and blue to produce a "pinker" random colour.
// Will produce a random colour with more red in it (usually "pink-ish")
float r = rand.nextFloat();
float g = rand.nextFloat() / 2f;
float b = rand.nextFloat() / 2f;
Or to ensure that only "light" colours are generated, you can generate colours that are always > 0.5 of each colour element:
// Will produce only bright / light colours:
float r = rand.nextFloat() / 2f + 0.5;
float g = rand.nextFloat() / 2f + 0.5;
float b = rand.nextFloat() / 2f + 0.5;
There are various other colour functions that can be used with the Color
class, such as making the colour brighter:
randomColor.brighter();
An overview of the Color
class can be read here: http://download.oracle.com/javase/6/docs/api/java/awt/Color.html
Get a Bright Random Colour Python
Create a random HLS color (using numbers around .5 as the "level" parameter and numbers above .5 as the "saturation" parameter) and convert them to RGB:
import random
import colorsys
h,s,l = random.random(), 0.5 + random.random()/2.0, 0.4 + random.random()/5.0
r,g,b = [int(256*i) for i in colorsys.hls_to_rgb(h,l,s)]
That will ensure you'll always have highly saturated, bright colors.
Related Topics
How to Add a Delay in a JavaScript Loop
How to Remove a Property from a JavaScript Object
JavaScript Post Request Like a Form Submit
How to Obfuscate (Protect) JavaScript
Simplest Code For Array Intersection in JavaScript
How to Set/Unset a Cookie With Jquery
Error: Can't Set Headers After They Are Sent to the Client
Uncaught Referenceerror: $ Is Not Defined
How to Create a File in Memory For User to Download, But Not Through Server
What Is the 'New' Keyword in JavaScript
How to Manage a Redirect Request After a Jquery Ajax Call
Weird Behavior With Objects & Console.Log
JavaScript by Reference Vs. by Value
A Partial View Passing a Collection Using the Html.Begincollectionitem Helper