Pixel-Composer/scripts/string_hexadecimal/string_hexadecimal.gml

68 lines
1.7 KiB
Plaintext
Raw Normal View History

function string_hexadecimal(str) {
2023-03-02 07:59:14 +01:00
static HEX = "0123456789ABCDEF";
2022-01-13 05:24:03 +01:00
var i = string_length(str);
var d = 1;
var v = 0;
while(i > 0) {
2024-04-20 05:00:28 +02:00
var ch = string_char_at(str, i);
2023-03-02 07:59:14 +01:00
var val = string_pos(string_upper(ch), HEX) - 1;
2022-01-13 05:24:03 +01:00
v += val * d;
d *= 16;
i--;
}
return v;
}
function number_to_hex(val) {
2023-02-28 09:43:01 +01:00
static HEX = "0123456789ABCDEF";
2022-01-13 05:24:03 +01:00
var ss = "";
while(val > 0) {
var i = val % 16;
ss = string_char_at(HEX, i + 1) + ss;
val = floor(val / 16);
}
while(string_length(ss) < 2) {
ss = "0" + ss;
}
return ss;
}
2024-05-15 12:42:54 +02:00
function color_get_hex(color, alpha = true) {
2023-03-31 06:59:08 +02:00
var arr = is_array(color) && array_length(color) == 4;
var r = arr? round(color[0] * 256) : color_get_red(color);
var g = arr? round(color[1] * 256) : color_get_green(color);
var b = arr? round(color[2] * 256) : color_get_blue(color);
var a = arr? round(color[3] * 256) : color_get_alpha(color);
2024-05-15 12:42:54 +02:00
return number_to_hex(r) + number_to_hex(g) + number_to_hex(b) + (alpha && is_int64(color)? number_to_hex(a) : "");
2022-11-18 03:20:31 +01:00
}
function color_from_rgb(str) {
2024-05-25 10:07:11 +02:00
if(string_length(str) < 6) return -1;
2022-11-18 03:20:31 +01:00
var _r = string_hexadecimal(string_copy(str, 1, 2));
var _g = string_hexadecimal(string_copy(str, 3, 2));
var _b = string_hexadecimal(string_copy(str, 5, 2));
2024-05-25 10:07:11 +02:00
if(string_length(str) == 8) {
var _a = string_hexadecimal(string_copy(str, 7, 2));
return make_color_rgba(_r, _g, _b, _a);
}
2022-11-18 03:20:31 +01:00
return make_color_rgb(_r, _g, _b);
2023-10-18 14:58:55 +02:00
}
function colorFromHex(hex) {
if(string_length(hex) != 6) return 0;
var rr = string_hexadecimal(string_copy(hex, 1, 2));
var gg = string_hexadecimal(string_copy(hex, 3, 2));
var bb = string_hexadecimal(string_copy(hex, 5, 2));
return make_color_rgb(rr, gg, bb);
2022-01-13 05:24:03 +01:00
}