How can I create a 256x256 color space image using graphics draw? Currently I'm using pointers to loop through each pixel location and setting it. Blue goes from 0...255 on X and Green goes from 0...255 on Y. The image is initialized as so.
Bitmap image = new Bitmap(256, 256);
imageData = image.LockBits(new Rectangle(0, 0, 256, 256),
ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);
for (int row = 0; row < 256; row++)
{
byte* ptr = (byte*)imageData.Scan0 + (row * 768);
for (int col = 0; col < 256; col++)
{
ptr[col * 3] = (byte)col;
ptr[col * 3 + 1] = (byte)(255 - row);
ptr[col * 3 + 2] = 0;
}
}
I have a slider that goes 0...255 on Red. On each scroll, it goes through this loop and updates the image.
for (int row 开发者_如何学C= 0; row < 256; row++)
{
byte* ptr = (byte*)imageData.Scan0 + (row * 768);
for (int col = 0; col < 256; col++)
{
ptr[col * 3 + 2] = (byte)trackBar1.Value;
}
}
I've figured out how to use a ColorMatrix instead for the scrolling part but how can I initialize the image without using pointers or SetPixel?
First of all, add PictureBox control to the Form.
Then, this code will assign different color to each pixel based on the index in the loop and assign the image to the control:
Bitmap image = new Bitmap(pictureBox3.Width, pictureBox3.Height);
SolidBrush brush = new SolidBrush(Color.Empty);
using (Graphics g = Graphics.FromImage(image))
{
for (int x = 0; x < image.Width; x++)
{
for (int y = 0; y < image.Height; y++)
{
brush.Color = Color.FromArgb(x, y, 0);
g.FillRectangle(brush, x, y, 1, 1);
}
}
}
pictureBox3.Image = image;
For some reason there's no SetPixel
or DrawPixel
like I expected, but the FillRectangle
will do exactly the same thing when you give it 1x1 dimensions to fill.
Note that it will work fine for small images but the larger the image the slower it will be.
If you don't want to use pointers or SetPixel you'll have to build the gradient in a byte array and then Marshal.Copy it to your bitmap:
int[] b = new int[256*256];
for (int i = 0; i < 256; i++)
for (int j = 0; j < 256; j++)
b[i * 256 + j] = j|i << 8;
Bitmap bmp = new Bitmap(256, 256, PixelFormat.Format32bppRgb);
BitmapData bits = bmp.LockBits(new Rectangle(0, 0, 256, 256),
ImageLockMode.ReadWrite, PixelFormat.Format32bppRgb);
Marshal.Copy(b, 0, bits.Scan0, b.Length);
This would create you a white image of 256x256
Bitmap image = new Bitmap(256, 256);
using (Graphics g = Graphics.FromImage(image)){
g.FillRectangle(Brushes.White, 0, 0, 256, 256);
}
精彩评论