Skip to content

Instantly share code, notes, and snippets.

@PlugFox
Last active April 22, 2024 15:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save PlugFox/27aa5f03cf9101043a50b29dc3c7d397 to your computer and use it in GitHub Desktop.
Save PlugFox/27aa5f03cf9101043a50b29dc3c7d397 to your computer and use it in GitHub Desktop.
Flutter HEX Color
void main() {
// Conver Dec to Hex
String dec2hex(int n) => n.toRadixString(16).toUpperCase();
// 32 bit number
int colorValue = 0xFFf2efed;
print('Hex color: ${dec2hex(colorValue)}');
print('Dec color: $colorValue');
// Extract colors
int alpha = (colorValue & 0xFF000000) >> 24;
int red = (colorValue & 0x00FF0000) >> 16;
int green = (colorValue & 0x0000FF00) >> 8;
int blue = (colorValue & 0x000000FF);
// Output
print("Alpha: $alpha or ${dec2hex(alpha)}"); // 255
print("Red: $red or ${dec2hex(red)}"); // 242
print("Green: $green or ${dec2hex(green)}"); // 239
print("Blue: $blue or ${dec2hex(blue)}"); // 237
}
@PlugFox
Copy link
Author

PlugFox commented Apr 22, 2024

Суть в том, что любой цвет можно записать 32 битным числом и записать в шестнадцатеричной системе счисления
(цифры идут не от 0 до 9, а от 0 до 9 и потом от A до F, где 16 в десятиричной равна F в шестнадцатеричной).
Тоесть у тебя есть в памяти 4 байта (каждый по 8 бит) и ты под каждую составляющую цвета отводишь 2 байта (числа от 0 до 255).
Специальными битвайз операциями и маской можно извлечь каждый кусочек.
И вроде как и просто обычное число получается, но вроде как и состоящее из 8 ячеек (по 2 ячейки на A, R, G, B).
Ну и сама запись человекочитаема, видно из чего состоит цвет, а не просто число "4294111213" и непойми что это.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment