上一篇文章写到如何绘制一个调色盘,并给出了核心算法代码。但还缺少一个步骤:显示该调色盘。
既然已经可以绘制一个调色盘了,那就必然要将调盘显示出来!如何显示呢?这就需要用到一个“可写的图片”。通过写一个图片,将调色盘的数据写入一个图片中,然后用Image控件显示出来即可。
不多做解释,代码如下:
// radius为调色盘的半径
private void GetColorWheel(int radius)
{
// 定义一个“可写的图片”对象
WriteableBitmap bitmap = new(radius * 2 + 1, radius * 2 + 1, 96, 96, PixelFormats.Pbgra32, null);
unsafe
{
bitmap.Lock();
IntPtr pointer = bitmap.BackBuffer; // 找到内存中的图像的首地址
for (int y = 0; y < bitmap.PixelHeight; y++)
{
for (int x = 0; x < bitmap.PixelWidth; x++)
{
Color c = GetColor(x, y, 255);
int offset = (x + y * bitmap.PixelWidth) * bitmap.Format.BitsPerPixel / 8;
Marshal.WriteByte(pointer, offset, c.B);
Marshal.WriteByte(pointer, offset + 1, c.G);
Marshal.WriteByte(pointer, offset + 2, c.R);
Marshal.WriteByte(pointer, offset + 3, 255); // 写入alpha值
}
}
Int32Rect rect = new(0, 0, bitmap.PixelWidth, bitmap.PixelHeight); // 要更新的区域
bitmap.AddDirtyRect(rect);
bitmap.Unlock();
}
// img为xaml中的Image控件。
img.Source = bitmap;
}
具体代码的含义,自行百度吧。