#963 – A Color Selection Box Organized by Hue, part II

In part I, I included source code for generating a list of sample colors.

To bind to a generated color list, we can call ColorUtil.GenerateColorList and make the result available via a property.  In the code sample below, we generate a list of 4,096 colors (16 values for red, green and blue).

public partial class MainWindow : Window, INotifyPropertyChanged
{
    public MainWindow()
    {
        this.InitializeComponent();
        this.DataContext = this;

         ColorList = ColorUtil.GenerateColorList(16);
    }

    private List<ColorWithInfo> colorList;
    public List<ColorWithInfo> ColorList
    {
        get { return colorList; }
        protected set
        {
            colorList = value;
            RaisePropertyChanged("ColorList");
        }
    }

    // INotifyPropertyChanged
    public event PropertyChangedEventHandler PropertyChanged = delegate { };

    private void RaisePropertyChanged(string propName)
    {
        PropertyChanged(this, new PropertyChangedEventArgs(propName));
    }
}

In our XAML, we can create a simple ComboBox that binds to this list.  We set the ItemTemplate to display each color as a simple rectangle and the ItemsPanel as a WrapPanel with a fixed width.

    <ComboBox Margin="15" Height="30" Width="200"
                ItemsSource="{Binding ColorList}"
                ScrollViewer.HorizontalScrollBarVisibility="Disabled">
        <ComboBox.ItemTemplate>
            <DataTemplate>
                <Grid>
                    <Rectangle Height="55" Width="55">
                        <Rectangle.Fill>
                            <SolidColorBrush Color="{Binding Color}"/>
                        </Rectangle.Fill>
                    </Rectangle>
                </Grid>
            </DataTemplate>
        </ComboBox.ItemTemplate>
        <ComboBox.ItemsPanel>
            <ItemsPanelTemplate>
                <WrapPanel IsItemsHost="True" Orientation="Horizontal" Width="1000"/>
            </ItemsPanelTemplate>
        </ComboBox.ItemsPanel>
    </ComboBox>

Below is an image showing the ComboBox in action. Note that the colors are sorted by hue, given that the GenerateColorList method sorted the color values this way.

963-001

#962 – A Color Selection Box Organized by Hue, part I

Here’s some code that generates a spread of different colors.  (We’ll later bind a ComboBox to the generated list of colors).

    public class ColorWithInfo : IComparable
    {
        public Color Color { get; set; }

        public string Info
        {
            get { return string.Format("{0}/{1}/{2}", Color.R, Color.G, Color.B); }
        }

        public string HueSatBright
        {
            get { return string.Format("{0}/{1}/{2}", Hue, Saturation, Brightness); }
        }

        public float Hue
        {
            get { return System.Drawing.Color.FromArgb(Color.R, Color.G, Color.B).GetHue(); }
        }

        public float Saturation
        {
            get { return System.Drawing.Color.FromArgb(Color.R, Color.G, Color.B).GetSaturation(); }
        }

        public float Brightness
        {
            get { return System.Drawing.Color.FromArgb(Color.R, Color.G, Color.B).GetBrightness(); }
        }

        public int CompareTo(object obj)
        {
            ColorWithInfo cwiOther = obj as ColorWithInfo;

            // Sort by Hue, and then Saturation, and then Brightness
            if (this.Hue == cwiOther.Hue)
            {
                if (this.Saturation == cwiOther.Saturation)
                    return this.Brightness.CompareTo(cwiOther.Brightness);
                else
                    return this.Saturation.CompareTo(cwiOther.Saturation);
            }
            else
                return this.Hue.CompareTo(cwiOther.Hue);
        }
    }

    public static class ColorUtil
    {
        public static List<ColorWithInfo> GenerateColorList(int numValsPerColor)
        {
            List<ColorWithInfo> colorList = new List<ColorWithInfo>();

            // Create increment such that we start at 0, end at 255,
            // and have a total of numValsPerColor within that range.
            int delta = Convert.ToInt32(255.0 / ((double)numValsPerColor - 1.0));

            for (int r = 0; r < numValsPerColor; r++)
                for (int g = 0; g < numValsPerColor; g++)
                    for (int b = 0; b < numValsPerColor; b++)
                    {
                        ColorWithInfo cwi = new ColorWithInfo {
                            Color = Color.FromRgb((byte)(r * delta), (byte)(g * delta), (byte)(b * delta))};
                        colorList.Add(cwi);
                    }

            colorList.Sort();

            return colorList;
        }
    }

#811 – Setting Color Values in Code Based on System Colors

You can set the Foreground or Background properties of a control to a brush that will render the control using one of the predefined system colors.  The SystemColors class contains a number of static SolidColorBrush objects representing brushes that match the system colors.

811-001

        <Label Name="lblMA" Content="Margaret Atwood" HorizontalAlignment="Center"
               Padding="20,10" Margin="10"
               Background="LightPink"/>
        <Button Content="Change Color" HorizontalAlignment="Center"
                Padding="10,5" Click="Button_Click"/>

 

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            // Set to one of the predefined brushes that map
            // to the system colors
            lblMA.Background = SystemColors.ActiveCaptionBrush;
        }

811-002
811-003

#553 – Setting an Alpha Value in Blend

Colors in WPF consist of 8 bytes–2 bytes each for the alpha, red, green and blue channels.  The alpha channel dictates the transparency/opacity of a color (255 or #FF = fully opaque, 0 = fully transparent).

You can set the alpha value for a color in the color editor in Blend by setting the value of the field labeled A (0-100%) or by explicitly setting the first two bytes of the hex value for the color (#00-#FF).

In the example below, the Alpha value is at 100%, or #FF, indicating that the color is fully opaque.

If you set the Alpha value to 50%, you’ll see that the first two bytes in the color value are now #7F (127).

In the example below, we’ve set the the Foreground color of the label to Black, with an alpha value of 50% so that we can see through the label to the GUI behind it.

#549 – More Colors Than You Know What to Do With

Pantone provides a color matching system that includes a list of 2,058 colors (the Pantone Goe system) that you can select from when selecting colors for print or for online applications.

Below is the full set of Pantone Goe colors.  To use any of these colors in a WPF application, simply use the color eyedropper tool in Blend to select the color that you want.

#547 – Specifying Colors by Name in Blend

When you are specifying color values for a color-valued property in Blend, there are several different ways to specify a color.  You can select a color by selecting it from the palette, use the eyedropper tool, or enter RGB values directly.

You can also specify a color by entering a color value by name in the text field that initially displays the color as a hex value.

Below is a list of all predefined colors, which you can reference by name.

 

#528 – Using the Eyedropper Tool in the Color Editor

In addition to the eyedropper tool on the tools panel, you can select colors using the eyedropper tool in the color editor, found in the Brushes panel.

To use the eyedropper, first select a control having a color property that you want to change.

In the Brushes section of the Properties panel, pick a property that you want to change.  (E.g. Background).

Select the kind of brush that you want to use (e.g. solid color brush).

Click on the eyedropper icon in the color editor.

Now you can move around the screen and click to pick up the color at the current mouse position.  You can click anywhere on the screen–even outside of Blend.

As you move around the screen, the target element will change to preview using the color of the pixel that your mouse is hovering over.  Left-click to actually use the color.

#527 – Colorful Expression Add-in Connects to Adobe Kuler

The Adobe Kuler web app lets you easily create various palettes of related colors.  The Colorful Expression project on Codeplex brings the functionality of Kuler into Expression Blend.

To use the Colorful Expression add-in:

  • Download the .zip file
  • Extract files to the Extensions sub-directory under the Blend directory (e.g. C:\Program Files (x86)\Microsoft Expression\Blend 4\Extensions)
  • Start Blend normally

You’ll now see a Colorful Expression entry under the Window menu.

When you enable this window, you’ll get a new window where you can search for or bring up color palettes from Kuler.

You can now drag and drop any of the palettes onto the artboard.  Doing this will create each of the colors in the palette as a static resource in your project.

You can now remove the Grid of colors and use the colors by using the resource name for the color.

 

#526 – Use Adobe Kuler to Create Color Themes

Adobe has created an online app, Adobe Kuler, that allows you to easily create sets of themed colors based on a starting color or an image.

You can create a set of colors starting with a single color by selecting the From a Color option and then selecting one of the rules.  (E.g. Analogous, Monochromatic, Triad, etc).

After you pick the rule, you can click and drag on the center circle (with double outline) to change the starting color.  You can also click on any of the other circles to effectively change the rule.

You can also generate a palette of colors by starting with a picture.  Here’s a set of colors based on a picture of my shed.

After Kuler generates the initial palette, you can  drag the little circles around to change which spots in the picture it uses to generate the palette.

 

#223 – Predefined System Colors

The System.Windows.SystemColors class contains a series of static properties that expose the current predefined system colors.  These are the predefined system colors that you can change from the Control Panel (Control Panel\Appearance and Personalization\Personalization\Window Color and Appearance in Windows 7).

The properties come in triplets.  For each system color Xxx, there are XxxBrush, XxxBrushKey and XxxColor properties.

Here’s a chart showing the default colors, under the Aero theme in Windows 7.  (Click on the image to see it full-sized).