'Making a discrete slider using Processing
How can I make my slider discrete using Processing? Here is my code. I need to make it discrete with values from 0-10. I already put some line indicators, what I only need is to make it discrete. Can you give me an idea of how to do it?
So far, all we have made right now are continuous sliders, and the thumb travels very smoothly. How can we add steps to the same slider to make a discrete slider? Here is an example of the same slider but with 10 steps instead of returning every value in between.
int x=75;
void setup() {
size(600,400);
}
void draw() {
background(100);
fill (200);
rect (75, 25, 400, 50);
stroke(0);
if(mousePressed) {
if (mouseX >75 && mouseX <= 475)
{x=mouseX;}
}
fill(127,0,0);
rect (x, 20, 9, 60);
fill (255);
// Left Button
fill (200);
rect (10, 25, 50, 50);
{
if (mousePressed == true) {
if (mouseX <= 50 && (mouseY >= 40 && mouseY <= 60)) {
fill(255);
if (x>100){
x-=20;
} else {
x=75;
}
} else {
fill(0);
}
}
if (mousePressed == false) {
fill (0);
}
triangle (50, 60, 50, 40, 15, 50);
}
// Right button
fill (200);
rect (490, 25, 50, 50);
{
if (mousePressed == true) {
if (mouseX >= 500 && (mouseY >= 40 && mouseY <= 60)) {
fill(255);
if (x<470){
x+=20;
}
else {
x=470;
}
} else {
fill(0);
}
}
if (mousePressed == false) {
fill (0);
}
triangle (500, 60, 500, 40, 535, 50);
}
println(x);
line (115, 60, 115, 90);
line (155, 60, 155, 90);
line (195, 60, 195, 90);
line (235, 60, 235, 90);
line (275, 60, 275, 90);
line (315, 60, 315, 90);
line (355, 60, 355, 90);
line (395, 60, 395, 90);
line (435, 60, 435, 90);
}
Solution 1:[1]
There are different aproaches to your problem:
The easiest implementation would be drawing the rectangle to the correct position but storing the x value as you already do.
The position of your lable in the slider is:
int length = 400; //lenght of the slider
int steps = 10; //steps for the slider
int start = 75; //start of the slider
int currentStep = round(((float)steps)*(x - start)/lenght);
//The float parse is important
//round(), ceil() or floor() will work
int correctedPos = round(((float)length)/steps*currentStep) + start;
Then just draw the rect at the correct position;
rect(correctedPos, 20, 9, 60);
The second option would be storing the currentStep and not the x that you already store. Your buttons will have to increment or decrease currentStep instead of x. Then you will also have to calculate the correctedPos as I have already shown.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
