c#随机产生颜色

有时为了满足现实的需要,我们想生成随机的较深的颜色,比如:彩色二维码,为了让手机、二维码识别设备可以正确识别,必须使用较深的颜色。
如下图所示:

彩色二维码样图1      彩色二维码样图2

 

那么,如何实现呢?以下为源码: 

 1 //C# Code:
 2 
 3 using System;
 4 using System.Drawing;
 5 
 6 namespace Lgms.Net.QRCode.Codec.Util
 7 {
 8     public class ColorUtil
 9     {
10         public static System.Drawing.Color GetRandomColor()
11         {
12             Random randomNum_1 = new Random(Guid.NewGuid().GetHashCode());
13             System.Threading.Thread.Sleep(randomNum_1.Next(1));
14             int int_Red = randomNum_1.Next(255);
15 
16             Random randomNum_2 = new Random((int)DateTime.Now.Ticks);
17             int int_Green = randomNum_2.Next(255);
18 
19             Random randomNum_3 = new Random(Guid.NewGuid().GetHashCode());
20 
21             int int_Blue = randomNum_3.Next(255);
22             int_Blue = (int_Red + int_Green > 380) ? int_Red + int_Green - 380 : int_Blue;
23             int_Blue = (int_Blue > 255) ? 255 : int_Blue;
24 
25 
26             return GetDarkerColor(System.Drawing.Color.FromArgb(int_Red, int_Green, int_Blue));
27         }
28 
29         //获取加深颜色
30         public static Color GetDarkerColor(Color color)
31         {
32             const int max = 255;
33             int increase = new Random(Guid.NewGuid().GetHashCode()).Next(30, 255); //还可以根据需要调整此处的值
34 
35 
36             int r = Math.Abs(Math.Min(color.R - increase, max));
37             int g = Math.Abs(Math.Min(color.G - increase, max));
38             int b = Math.Abs(Math.Min(color.B - increase, max));
39 
40 
41             return Color.FromArgb(r, g, b);
42         }
43 }

第二种方式:

 1 public System.Drawing.Color GetRandomColor()
 2 {
 3      Random RandomNum_First = new Random((int)DateTime.Now.Ticks);
 4      //  对于C#的随机数,没什么好说的
 5      System.Threading.Thread.Sleep(RandomNum_First.Next(50));
 6      Random RandomNum_Sencond = new Random((int)DateTime.Now.Ticks);
 7  
 8      //  为了在白色背景上显示,尽量生成深色
 9      int int_Red = RandomNum_First.Next(256);
10      int int_Green = RandomNum_Sencond.Next(256);
11      int int_Blue = (int_Red + int_Green > 400) ? 0 : 400 - int_Red - int_Green;
12      int_Blue = (int_Blue > 255) ? 255 : int_Blue;
13 14 return System.Drawing.Color.FromArgb(int_Red, int_Green, int_Blue); 15 }

 

posted @ 2017-06-27 09:15  marblemm  阅读(1432)  评论(0编辑  收藏  举报