我正在尝试创建一个显示原色的草图,然后使用按钮或滑块控制其透明度。我正在使用CntrolP5库。问题是,每当我将透明度变量放入颜色()时,一切都搞砸了,颜色甚至都没有出现。
见代码:
import controlP5.*;
ControlP5 cp5;
int transparency;
color c = color(0, 160, 25);
color red;
color green;
color blue;
void setup() {
size(400, 600);
gui();
red = color(255, 0, 0, transparency); // WHWENEVER I PUT TRASNPARENCY VALUE DOES NOT WORK
green = color(0, 255, 0, transparency);
blue = color(0, 0, 255, transparency);
noStroke();
smooth();
}
// create gui
void gui() {
cp5 = new ControlP5(this);
// create radio button
cp5.addRadioButton("radio")
.setPosition(40, 200)
.setItemWidth(20)
.setItemHeight(20)
.addItem("red", 0)
.addItem("green", 1)
.addItem("blue", 2)
.setColorLabel(color(255))
.activate(2)
;
cp5.addRadioButton("level")
.setPosition(100, 200)
.setItemWidth(20)
.setItemHeight(20)
.addItem("ONE", 0)
.addItem("TWO", 1)
.addItem("THREE", 2)
.addItem("FOUR", 3)
.addItem("FIVE", 4)
.addItem("SIX", 5)
.addItem("SEVEN", 6)
.addItem("EIGHT", 7)
.addItem("NINE", 8)
.addItem("TEN", 9)
.setColorLabel(color(255))
.activate(2)
;
//add slider bar
/* cp5.addSlider("level")
.setPosition(60,20)
.setSize(100,20)
.setRange(0,10)
.setValue(5)
.setNumberOfTickMarks(11)
.setSliderMode(Slider.FLEXIBLE)
;*/
}
void radio(int theC) {
switch (theC) {
case (0):
c = red;
break;
case (1):
c = green;
break;
case (2):
c = blue;
break;
}
}
void level(int theC) {
switch (theC) {
case (0):
transparency = 15;
break;
case (1):
transparency = 13;
break;
case (2):
transparency = 11;
break;
case (3):
transparency = 9;
break;
case (4):
transparency = 7;
break;
case (5):
transparency = 6;
break;
case (6):
transparency = 5;
break;
case (7):
transparency = 4;
break;
case (8):
transparency = 2;
break;
case (9):
transparency = 1;
break;
}
}
void draw() {
background(220);
fill(c); //fill with color
ellipse(200, 400, 100, 100);
}
答案 0 :(得分:1)
首先,您的代码不完整。例如,在调用setup()
时很难看到。如果它刚刚开始(如设置),则您的transparency
变量可能具有值0(因为它未初始化)并且颜色将完全透明。
其次,alpha值应该是介于0.0和1.0之间的浮点数或0到255之间的整数。在您的情况下,您将透明度值设置得非常低(最高值为15),因此您的颜色会非常透明。请尝试使用此代码:
void level(int theC) {
switch (theC) {
case (0):
transparency = 255;
break;
case (1):
transparency = 230;
break;
case (2):
transparency = 200;
break;
case (3):
transparency = 170;
break;
case (4):
transparency = 140;
break;
case (5):
transparency = 110;
break;
case (6):
transparency = 80;
break;
case (7):
transparency = 50;
break;
case (8):
transparency = 20;
break;
case (9):
transparency = 0;
break;
}
}
我希望它有所帮助。
答案 1 :(得分:1)
您在setup()
内初始化了颜色(红色,绿色,蓝色)的变量,您永远不会更改它们。如果您想要更改透明度,则需要移入draw()
,并且变量transparency
需要初始化为某个值。
此外,只有当用户点击" radio"要改进这个按钮,你需要从`radio()
中抽象颜色逻辑void radio(int theC) {
mode = theC;
}
其中mode
是存储颜色模式的整数变量。并更新了draw()
函数:
void draw() {
background(220);
switch (mode) {
case (0):
c = color(255, 0, 0, transparency);
break;
case (1):
c = color(0, 255, 0, transparency);
break;
case (2):
c = color(0, 0, 255, transparency);
break;
}
fill(c); //fill with color
ellipse(200, 400, 100, 100);
}
正如@rlinden正确提到的那样,你也应该将alpha值更新为0-255。