IOLink C# 1.11.0
Loading...
Searching...
No Matches
ColorWheel.cs

This code demonstrates how to draw a color wheel into a RGBA ImageView. The part outside the wheel is transparent, using alpha channel.

using IOLink;
using System;
using System.Numerics;
using System.Runtime.Intrinsics;
namespace Examples
{
public class ColorWheel
{
private static Vector3u8 HsvToRgb(double h, double s, double v)
{
double hp = h / 60.0;
double c = s * v;
double x = c * (1 - Math.Abs((hp % 2) - 1));
double m = v - c;
double r = 0, g = 0, b = 0;
if (hp <= 1)
{
r = c;
g = x;
}
else if (hp <= 2)
{
r = x;
g = c;
}
else if (hp <= 3)
{
g = c;
b = x;
}
else if (hp <= 4)
{
g = x;
b = c;
}
else if (hp <= 5)
{
r = x;
b = c;
}
else
{
r = c;
b = x;
}
Vector3d rgb_double = new Vector3d( r, g, b);
rgb_double += Vector3d.CreateUniform(m);
rgb_double *= 255.0;
return new Vector3u8((byte)rgb_double[0], (byte)rgb_double[1], (byte)rgb_double[2]);
}
private static ImageView Generate(VectorXu64 shape)
{
// first we can check if given shape has exactly 2
// dimensions
if (shape.Size() != 2)
{
throw new ApplicationException("Shape must have 2 dimensions");
}
// To create a RGBA ImageView, the datatype of the
// image must have 4 components, and so should be be
// VEC4_XXX (with XXX: INT8, INT16, INT32, INT64,
// UINT8, ...) We choose VEC4_UINT8 as the datatype
// for this example.
DataType dt = DataTypeId.VEC4_UINT8;
// create an image view in CPU memory
ImageView image = ImageViewFactory.Allocate(shape, dt);
// indicate the created image is a 2D IMAGE with RGB
// color interpretation and alpha channel
image.AxesInterpretation = ImageTypeId.IMAGE;
image.ImageInterpretation = ImageInterpretation.RGB;
image.HasAlpha = true;
// draw the color wheel
// all pixels outside the wheel are transparent
// (alpha=0)
Vector2d center = new Vector2d(shape[0] / 2.0, shape[1] / 2.0);
for (ulong y = 0; y < shape[1]; ++y)
{
for (ulong x = 0; x < shape[0]; ++x)
{
Vector2d position = new Vector2d((double)x, (double)y);
Vector2d delta = position - center;
VectorXu64 positionPixel = new VectorXu64(x, y);
double r = delta.Length();
if (r > center[0])
{
// write transparent pixel
// use a byte array with 4 elements
// (RGBA)
byte[] pixVal = { 0, 0, 0, 0 };
image.Write(positionPixel, pixVal);
}
else
{
// determine HSV value for current pixel
// position
double h = Math.Atan2(delta[1], delta[0]) * 180 / Math.PI + 180;
double s = r / center[0];
double v = 1;
// convert HSV to RGB
var rgb = ColorWheel.HsvToRgb(h, s, v);
// write RGBA pixel (with alpha = 255)
// use a byte array with 4 elements
// (RGBA)
byte[] pixVal = { rgb[0], rgb[1], rgb[2], 255 };
image.Write(positionPixel, pixVal);
}
}
}
return image;
}
public static void Main(string[] args)
{
ImageView image = Generate(new VectorXu64(512, 512));
Console.WriteLine("Generated image: " + image.ToString());
Console.WriteLine("SUCCESS");
}
}
}
Definition CreateDataFrame.cs:6