2013-05-07 27 views
0

我今天要產生在C#中的隨機顏色。爲什麼我收到「無法從‘詮釋’到‘字節’轉換,當我嘗試生成C#隨機顏色?

Random randomGenerator = new Random(); 
Color randomColor = Color.FromArgb(randomGenerator.Next(1, 255), 
            randomGenerator.Next(1, 255), 
            randomGenerator.Next(1, 255), 
            randomGenerator.Next(1, 255)); 

但VS2012口口聲聲說這樣的說法1/2/3/4:

不能從「詮釋」到「字節」轉換

此外,我試圖找到System.Drawing.Color,但無法找到它。與相同。

+5

投以字節.... – 2013-05-07 03:06:35

+0

從米奇..following上,'(字節)randomGenerator.Next(1,255) '... – 2013-05-07 03:07:40

+0

你嘗試從int轉換爲字節嗎? :) – Patashu 2013-05-07 03:10:40

回答

3

Random.Next返回int,但是FromArgb需要byte

所以,你需要將整數轉換爲字節:

randomColor = Color.FromArgb((byte)randomGenerator.Next(1, 255), 
       (byte)randomGenerator.Next...` 
0

由於INT有更多的範圍內,那麼字節,所以你需要顯式類型皈依

+0

是的,但我不認爲這是完全正確的答案。 – gunr2171 2013-05-07 03:28:49

1

您可以只投的隨機值類型「字節「該法預計:

Color randomColor = Color.FromArgb((byte)randomGenerator.Next(1, 255), 
            (byte)randomGenerator.Next(1, 255), 
            (byte)randomGenerator.Next(1, 255), 
            (byte)randomGenerator.Next(1, 255)); 

此外,你可能看不到的System.Drawing.Color因爲,我猜,你在一個WPF應用程序是,你會需要添加到SYST參考em.Drawing,但是你應該在System.Timers.Timer下有一個Timer對象。

0

您可以將任何數量的argb用下面的代碼顏色:

 Color color; 
     int num = 255; 
     double d = 205.0/(num + 256); 

     int red = Math.Min((int)(d * 256), 255); 
     int green = Math.Min((int)((d * 256 - red) * 256), 255); 
     int blue = Math.Min((int)(((d * 256 - red) * 256 - green) * 256), 255); 

     color = Color.FromArgb(red, green, blue); 
+0

你的回答並不關注最初由用戶user2356729提出的問題。 – 2015-01-28 17:37:04

相關問題