-
Notifications
You must be signed in to change notification settings - Fork 6
Colors of Control
A control has several parts, and each part may have different color depending on conditions. For example, a button changes its background color and border color when it is hovered and pressed. As the picture shows:
In order to simplify color setting, color pickers are introduced to set colors to parts in control. A color picker is a function object, as the definition shows below:
typedef std::function<zaf::Color(const zaf::Control& control)> ColorPicker;
The parameter is a control instance which type is the base class zaf::Control
, it my need to be down-casted if the control is a derived class actually. Typical implement of a color picker is: check the conditions of control, and then return a corresponding color. Below is an example that returns different color when the control is hovered and pressed:
auto color_picker = [](const zaf::Control& control) {
if (control.IsHovered()) {
return zaf::Color::Blue;
}
else {
return zaf::Color::Green;
}
};
After defining a color picker, it needs to be associated with a part of control. Background and border are basic parts of a control, and their color pickers can be accessed via GetBackgroundColorPicker
\ SetBackgroundColorPicker
and GetBorderColorPicker
\ SetBorderColorPicker
methods. The code shows below creates a control which exchanges its background color and border color when it is hovered:
//Create a control.
auto control = zaf::Create<zaf::Control>();
//Define a color picker.
auto color_picker = [](const zaf::Control& control, bool reverse) {
if (control.IsHovered() ^ reverse) {
return zaf::Color::White;
}
else {
return zaf::Color::Black;
}
};
//Associate the color picker with background and border.
control->SetBackgroundColorPicker(std::bind(color_picker, false));
control->SetBorderColorPicker(std::bind(color_picker, true));
Color pickers provide a flexible way to set color. However, sometimes defining color pickers is inconvenient when colors are consistent. Therefore zaf provides CreateColorPicker
function to help to create a stateless color picker. Passing an expected color to this function, it would transform the color to a corresponding color picker, as the code show:
//Create a stateless color picker.
auto color_picker = zaf::CreateColorPicker(zaf::Color::Black);
//Associate the color picker with border.
control->SetBorderColorPicker(color_picker);
Further more, besides accessor methods of color pickers, control also provides methods to access colors directly. For example, GetBackgroundColor
and SetBackgroundColor
methods are used to access background color; GetBorderColor
and SetBorderColor
methods are used to access border color. Getter methods return colors that are returned by color pickers. And setter methods are wrappers to CreateColorPicker
function actually.