有逗比小伙伴問我,數學的 π 視覺效果是啥,于是我就來寫一個逗比的應用將 π 的顏色在 WPF 應用畫出來,原理就是讀取 π 的小數點后的數值,然后使用逗比演算法轉換為 RGB 顏色像素,接著將這些像素轉換為一張圖片
以下就是我用程式生成的 π 圖片

我先從某個有趣的地方隨便找到了 π 小數點之后很長的數值,接下來將這個數值存放作為字串,再對這個字串執行如下演算法
- 讀取兩個 0-9 的字符
- 將此兩個字符拼接為兩位數的數值
- 將這些數值放在一個串列
此時就可以獲取這個串列的內容
如以下代碼,下面代碼的 NumberText.PI 就是一個 π 的字串
private static List<int> StringNumberToList()
{
var stringReader = new StringReader(NumberText.PI);
stringReader.Read();
stringReader.Read();
var list = new List<int>();
while (true)
{
var height = ReadNumber(stringReader);
if (height < 0)
{
break;
}
var low = ReadNumber(stringReader);
if (low < 0)
{
break;
}
var number = height * 10 + low;
list.Add(number);
}
return list;
}
private static int ReadNumber(StringReader reader)
{
while (true)
{
var text = reader.Read();
if (text == -1)
{
return -1;
}
var c = (char)text;
var n = c - '0';
if (n is >= 0 and <= 9)
{
return n;
}
}
}
接下來通過 WriteableBitmap 將上面生成的數值串列轉換為 RGB 像素寫入到圖片,演算法如下
- 按照順序遍歷數值串列
- 按照 BGR 的順序填充像素的數值
- 像素每個數值計算方法是按照 0-100 的比例對應 0-255 的比例拉伸
代碼如下
private static unsafe WriteableBitmap ToBitmap(List<int> list, double width, double height)
{
var writeableBitmap = new WriteableBitmap((int)width, (int)height, 96, 96, PixelFormats.Bgra32, null);
writeableBitmap.Lock();
var backBuffer = (byte*)writeableBitmap.BackBuffer;
var length = writeableBitmap.PixelWidth * writeableBitmap.PixelHeight *
writeableBitmap.Format.BitsPerPixel / 8;
for (int i = 0, j = 0; i + 4 < length && j + 3 < list.Count; i = i + 4, j += 3)
{
var blue = backBuffer[i];
var green = backBuffer[i + 1];
var red = backBuffer[i + 2];
var alpha = backBuffer[i + 3];
blue = (byte)Math.Round(list[j + 2] / 100.0 * byte.MaxValue);
green = (byte)Math.Round(list[j + 1] / 100.0 * byte.MaxValue);
red = (byte)Math.Round(list[j + 0] / 100.0 * byte.MaxValue);
alpha = 0xFF;
backBuffer[i] = blue;
backBuffer[i + 1] = green;
backBuffer[i + 2] = red;
backBuffer[i + 3] = alpha;
}
writeableBitmap.AddDirtyRect(new Int32Rect(0, 0, writeableBitmap.PixelWidth, writeableBitmap.PixelHeight));
writeableBitmap.Unlock();
return writeableBitmap;
}
通過上面代碼就可以拿到 π 的圖片,將此圖片在界面顯示就可以看到效果
當然了,除了以上演算法之外,還有其他很多有趣的方法,歡迎大家亂寫
本文所有代碼放在 github 和 gitee 歡迎訪問
可以通過如下方式獲取本文的源代碼,先創建一個空檔案夾,接著使用命令列 cd 命令進入此空檔案夾,在命令列里面輸入以下代碼,即可獲取到本文的代碼
git init
git remote add origin https://gitee.com/lindexi/lindexi_gd.git
git pull origin 747c17ef199dddf7f13f8cae7ffc9aefc9d117ad
以上使用的是 gitee 的源,如果 gitee 不能訪問,請替換為 github 的源
git remote remove origin
git remote add origin https://github.com/lindexi/lindexi_gd.git
獲取代碼之后,進入 KohaykowurchemJaibuqajijiyeco 檔案夾
博客園博客只做備份,博客發布就不再更新,如果想看最新博客,請到 https://blog.lindexi.com/

本作品采用知識共享署名-非商業性使用-相同方式共享 4.0 國際許可協議進行許可,歡迎轉載、使用、重新發布,但務必保留文章署名[林德熙](http://blog.csdn.net/lindexi_gd)(包含鏈接:http://blog.csdn.net/lindexi_gd ),不得用于商業目的,基于本文修改后的作品務必以相同的許可發布,如有任何疑問,請與我[聯系](mailto:[email protected]),
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/295798.html
標籤:.NET技术
