I was trying to implement a color scale which should be place beside a graph. The first idea was to use a 64 by 1 grid and fill each grid's cell with an appropriate color. But the result looked quite unexpected:
Of course I did set all margin, border and stroke size to zero, but the problem seems to come from the rounding to the pixel grid of the screen of each cell's size compared with the container's size.
Thus the next idea was to draw rectangle and here again the same problem raised. So I figured out that one needed a completely new approach:
The basic idea is to generate a bitmap image on the fly which is 1 pixel wide and n pixels in height where n also corresponds to the number of colors of the color scale. Then one can scale the bitmap to fill the container:
Here is the complete code:
public void CompleteColorScale()
{
int
Size = 64;
double
RectHeight = (int)(DrawPlane.ActualHeight /
Size);
double
RectWidth = (int)DrawPlane.ActualWidth;
int
width=1;
int
height=Size;
WriteableBitmap
bitmap = new WriteableBitmap(width,
height, 96, 96, PixelFormats.Bgra32, null);
int
red;
int
green;
int
blue;
int alpha;
uint[]
pixels = new uint[width
* height];
for
(int i = 0; i < Size; i++)
{
red = 0;
green = 255 * i / height;
blue = 255 ;
alpha = 255;
pixels[i] = (uint)((blue << 24) + (green << 16) + (red
<< 8) + alpha);
}
bitmap.WritePixels(new Int32Rect(0,
0, width, height), pixels, width * 4, 0);
DrawPlane.Source = bitmap;
DrawPlane.Stretch = Stretch.Fill;
}
<Grid Name="ColorScale" Loaded="ColorScale_Loaded"><Image Name="DrawPlane">Image>Grid>
No comments:
Post a Comment