Search code examples
c#windows-runtimewindows-8.1search-box

WinRT: How to create an image file or stream filled with one color for SearchBox suggestions


I´m writting a windows 8.1 Store App which displays all system colors in a GridView and a SearchBox on the top. When I type in a search query I want the suggestions to display result suggestions with a rectangle filled with the suggested color, but I´m unable to set a DataTemplate. The only way to provide that rectangle is as an image within a IRandomAccessStreamReference.

So, how do I get a rectangle of lets say 100x100 pixel in that suggestion?


Solution

  • You can use RandomAccessStreamReference.CreateFromStream to create a IRandomAccessStreamReference for AppendResultSuggestion you only need a RandomAccessStream containing the image data.

    For that you can use following method:

    private async Task<InMemoryRandomAccessStream> CreateInMemoryImageStream(Color fillColor, uint heightInPixel, uint widthInPixel)
        {
            var stream = new InMemoryRandomAccessStream();
    
            var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId,stream);
    
            List<Byte> bytes = new List<byte>();
            for (int x = 0; x < widthInPixel; x++)            
            {
                for (int y = 0; y < heightInPixel; y++)
                {
                    bytes.Add(fillColor.R);
                    bytes.Add(fillColor.G);
                    bytes.Add(fillColor.B);
                    bytes.Add(fillColor.A);                   
                }   
            }
    
            encoder.SetPixelData(BitmapPixelFormat.Rgba8, BitmapAlphaMode.Ignore, widthInPixel, heightInPixel, 96, 96, bytes.ToArray());
            await encoder.FlushAsync();
            return stream;
        }
    

    After that you can call:

    args.Request.SearchSuggestionCollection.AppendResultSuggestion("Green", string.Empty, string.Empty, await CreateInMemoryImageStream(Colors.Green), string.Empty);
    

    I know it looks quite hacky but it works like a charm!