最近开发项目中,需要自己绘制一张离散的噪点图。研究了好久,终于实现了。

其中我们使用了正态分布。正态分布(英语:normal distribution)又名高斯分布(英语:Gaussian distribution),是一个非常常见的连续概率分布。

这里就不过多介绍了,对正态分布不了解的,可以自己百度一下https://baike.baidu.com/item/%E6%AD%A3%E6%80%81%E5%88%86%E5%B8%83/829892?fr=aladdin

正态分布公式如下:
首先,我们要做的就是,把上面的公式转换成可执行代码,如下:

  1. 1 /// <summary>
  2. 2 /// 高斯分布概率模型
  3. 3 /// </summary>
  4. 4 /// <param name="_x">随机变量</param>
  5. 5 /// <param name="_μ">位置参数</param>
  6. 6 /// <param name="_σ">尺度参数</param>
  7. 7 /// <returns></returns>
  8. 8 private static float NormalDistribution(float _x, float _μ, float _σ)
  9. 9 {
  10. 10 float _inverseSqrt2PI = 1 / Mathf.Sqrt(2 * Mathf.PI);
  11. 11 float _powOfE = -(Mathf.Pow((_x - _μ), 2) / (2 * _σ * _σ));
  12. 12 float _result = (_inverseSqrt2PI / _σ) * Mathf.Exp(_powOfE);
  13. 13 return _result;
  14. 14 }

假设我们要绘制一张大小为1024*1024,从中心向四周逐渐稀疏,并且颜色越来越淡的噪点图,代码如下:

  1. 1 /// <summary>
  2. 2 /// 通过高斯分布公式绘制一张离散效果图
  3. 3 /// </summary>
  4. 4 /// <param name="_centerPoint">中心点坐标</param>
  5. 5 /// <param name="_consi">图颜色的阿尔法值</param>
  6. 6 /// <returns></returns>
  7. 7 public Texture2D CreateTeture2D(Vector2 _centerPoint, float _consi)
  8. 8 {
  9. 9 Texture2D _newTex = new Texture2D(1024, 1024, TextureFormat.ARGB32, true);
  10. 10 Color[] _colorBase = new Color[1024 * 1024];
  11. 11 int _hwidth = (int)(1024 * _centerPoint.x);
  12. 12 int _hheight = (int)(1024 * _centerPoint.y);
  13. 13
  14. 14 float _per;
  15. 15 int _index;
  16. 16 for (int i = 0; i < 1024; i++)
  17. 17 {
  18. 18 for (int j = 0; j < 1024; j++)
  19. 19 {
  20. 20 _per = (Mathf.Sqrt((i - _hwidth) * (i - _hwidth) + (j - _hheight) * (j - _hheight))) / 512;
  21. 21 float _tr = NormalDistribution(_per, 0, 1); //float _tr = NormalDistribution(0, 0, 1)=0.3989423f;也就是说中心点的概率为0.3989423f,即最大概率
  22. 22 bool _drawing = Random.Range(0, 0.3989423f) < _tr ? true : false;
  23. 23 if (_drawing)
  24. 24 {
  25. 25 _index = i * 1024 + j;
  26. 26 _colorBase[_index] = new Color(1, 0, 0, _tr * _consi);
  27. 27 }
  28. 28 else
  29. 29 {
  30. 30 _colorBase[i * 1024 + j] = new Color(0, 0, 0, 0);
  31. 31 }
  32. 32 }
  33. 33 }
  34. 34 _newTex.SetPixels(_colorBase);
  35. 35 _newTex.Apply();
  36. 36 _colorBase = null;
  37. 37 System.GC.Collect();
  38. 38 return _newTex;
  39. 39 }

当中心点坐标为(0.5,,05),颜色阿尔法值为1时,效果如下:

当中心点坐标为(0.2,0.3)时,效果如下:

我们可以将 _colorBase[_index] = new Color(1, 0, 0, _tr * _consi );这句代码更改为:_colorBase[_index] = new Color(1, 0, 0, _tr * _consi * (1 – _per));这样绘制的图,颜色从中心点渐变到边缘时,会完全透明,效果如下:

 

版权声明:本文为xiaoyulong原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/xiaoyulong/p/11334977.html