我想将画布分成8个垂直的黑白条纹。我写了一个方法changeValue来在每次执行循环时更改颜色的值,但画布是完全白色的。我认为我的changeValue方法没有按照假设做,但我无法解释原因。
到目前为止,我得到了这个:
public class Stripe {
public boolean switch = false;
private void stripes(int[] pixels, int width, int height) {
// TODO set some values here
int counter = 1;
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
int pos = y * width + x;
int r, g, b;
// TODO code for the flag.
r = 255;
g = 255;
b = 255;
for (int i = 0; i < 8; i++) {
if (x < (counter * (width - 1)) / 8) {
r = changeValue();
g = changeValue();
b = changeValue();
}
counter++;
switch ^= true;
}
pixels[pos] = 0xFF000000 | (r << 16) | (g << 8) | b;
}
}
}
public int changeValue() {
if (switch) {
return 255;
} else {
return 0;
}
}
}
我不应该为8条纹编写8 If语句,但这例如是意大利国旗的代码,它是3条垂直条纹但实际上有效:
private void flagItalian(int[] pixels, int width, int height) {
// TODO set some values here
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
int pos = y * width + x;
int r, g, b;
// TODO code for the flag.
r = 255;
g = 0;
b = 0;
if (x < 2 * (width - 1) / 3) {
r = 255;
g = 255;
b = 255;
}
if (x < (width - 1) / 3) {
r = 0;
g = 255;
b = 0;
}
pixels[pos] = 0xFF000000 | (r << 16) | (g << 8) | b;
}
}
}
答案 0 :(得分:0)
如果您需要交替颜色条纹,那么您可以选择经典的奇数/偶数检查。而不是你下面的代码块
for (int i = 0; i < 8; i++) {
if (x < (counter * (width - 1)) / 8) {
r = changeValue();
g = changeValue();
b = changeValue();
}
counter++;
switch ^= true;
}
尝试替换这个
if (x%2) {
r = 255;
g = 255;
b = 255
} else {
r = 0;
g = 0;
b = 0;
}