2013-09-26 47 views
3

嗯,我試圖隨機產生一種顏色,但有限制。Android - 如何生成一個隨機顏色的限制?

通過使RGB顏色僅49.

介於0和它應該使這樣的:color.nextInt(50);對?

這是繪製平方活動代碼:

public class Draw extends View 
{ 
    public Draw(Context context) 
    { 
     super(context); 
    } 

    Paint prop = new Paint(); 
    Random color = new Random(); 

    @Override 
    protected void onDraw(Canvas canvas) 
    { 
     super.onDraw(canvas); 

     int width = getWidth(); 
     int height = getHeight(); 

     int oriwidth = 0; 
     int oriheight = 0;  

     for (int x = 0; x < 20; x++) 
     { 
      int red = color.nextInt(50); 
      int green = color.nextInt(50); 
      int blue = color.nextInt(50); 

      prop.setARGB(0, red, green, blue); 
      canvas.drawRect(oriwidth += 10, oriheight += 10, width -= 10, height -= 10, prop); 
     } 
    } 
} 

,其結果是在白色的完整的四邊形。沒有限制,我會很好。

你能讓我明白在一組值之間畫一個正方形嗎?

感謝您的幫助,併爲英語感到抱歉。

+1

是否有你將α設置爲0(不可見)的原因? – Geobits

+0

真的嗎?它的工作原理沒有限制...它現在可以工作...只需將其設置爲255.我真的很笨:P感謝您的幫助。 –

回答

2

setArgb的第一個參數是透明度。您應該始終將其設置爲255.

+0

嗯,我不認爲這是因爲在我設定了它的工作極限(而且alpha在0)之後......我太笨了......「現在它可以工作,謝謝! –

0

爲什麼您被限制爲50,因爲最高限制是255。

int min = 0; 
int max = 255; 
int transparency=255;// from 0 to 255 ,255 means no transparency 

Random r = new Random(); 
int red = r.nextInt(max - min + 1) + min; 
int green= r.nextInt(max - min + 1) + min; 
int blue= r.nextInt(max - min + 1) + min; 
prop.setARGB(transparency, red, green, blue); 

通過改變min,max,可以限制顏色組合。 謝謝

0

就像我在評論中說的,你需要設置它的alpha透明度來顯示。

它「沒有限制」的原因是因爲你已經溢出了每個組件的範圍0...255。不帶參數的nextInt()會從0...MAX_INT-1生成一個數字。

要明白爲什麼重要,檢查出的Paint#setARGB()來源:

public void setARGB(int a, int r, int g, int b) { 
    setColor((a << 24) | (r << 16) | (g << 8) | b); 
} 

所有它做的是轉移和「包裝」 int值合併成一個。如果您超出每個組件一個字節的範圍,則行爲是「未定義」。如果你解壓到的組件,你可以看到這個問題

(a << 24) = 0 
(r << 16) = 16777216 
(g << 8) = 0 
(b)  = 0 
(final) = 16777216 

現在:例如,如果你試圖定義一種顏色爲ARGB = 0,256,0,0,你得到這個。 16777216 >> 24 = 1,所以它得到的阿爾法和所有其餘的都歸零。所以,有效的,你現在有一個顏色ARGB = 1,0,0,0


基本上,你分配一個字母,當你運行它「無極限」,但它是完全無意的。請記住,即使明確指定字母,最多隻能將組件限制爲255,否則最終會出現意外的結果。