What does the stride
parameter do in the CopyPixels
method?
Feel free to help with the other lines that have a comment if you wish.
BitmapSource bitmapSource = ColorSquare.Source as BitmapSource;
if (bitmapSource != null)
{
double x = Mouse.GetPosition(ColorSquare).X;
//This next line is confusing. It seems like I'm just dividing an image by itself
//say the image width is 4 and since I'm using it as the bitmap source the
//both the PixelWidth and the ActualWidth will = 4, right? Basically x *= 1;
x *= bitmapSource.PixelWidth / ColorSquare.ActualWidth;
if ((int)x > bitmapSource.PixelWidth - 1)
x = bitmapSource.PixelWidth - 1;
else if (x < 0) x = 0;
double y = Mouse.GetPosition(ColorSquare).Y;
y *= bitmapSource.PixelHeight / ColorSquare.ActualHeight;
if ((int)y > bitmapSource.PixelHeight - 1)
y = bitmapSource.PixelHeight - 1;
else if (y < 0) y = 0;
CroppedBitmap cb = new CroppedBitmap(bitmapSource, new Int32Rect((int)x, (int)y, 1, 1));
byte[] pixels = new byte[4];
//What is the stride and why does it need to be 4?
cb.CopyPixels(pixels, 4, 0);
if (pixels[3] == byte.MaxValue)
{
//So it seems we are passing all 4 pixels we copied earlier into the array
//here. This would be the Alpha,Red,Green,Blue of a color. So is that what stride does?
color = Color.FromArgb(pixels[3], pixels[2], pixels[1], pixels[0]);
}
}
To answer your question, it's 4 because you are asking for 4 pixels (it seems). However stride (as referred to in the method parameter) is just referring to how many pixels you want.
However, let's dig deeper.
Stride (Line stride) is essentially the length of a scan line in memory (padded or otherwise). Meaning, if you had to iterate over a 1 dimensional array of an image, you can use it to calculate pixel and lines (among other things)
Which is opposed to a Pixel Stride, the amount of bytes a pixel takes up in memory. A 32 bits per pixel image, will have 4 bytes (32 bits) or Uint per pixel.
Summary
Additional Resources
CopyPixels(Array, Int32, Int32)
Copies the bitmap pixel data into an array of pixels with the specified stride, starting at the specified offset.
Parameters
pixels -
Array
The destination array.stride -
Int32
The stride of the bitmap.offset -
Int32
The pixel location where copying starts.