mirror of
https://github.com/RGBCube/serenity
synced 2025-07-26 08:17:45 +00:00
LibGfx: Add a naive "rgba(r,g,b,a)" color parser
It's not very whitespace tolerant but it works.
This commit is contained in:
parent
8a40294f42
commit
b7339745d0
1 changed files with 41 additions and 0 deletions
|
@ -34,6 +34,7 @@
|
||||||
#include <LibIPC/Decoder.h>
|
#include <LibIPC/Decoder.h>
|
||||||
#include <ctype.h>
|
#include <ctype.h>
|
||||||
#include <stdio.h>
|
#include <stdio.h>
|
||||||
|
#include <stdlib.h>
|
||||||
|
|
||||||
namespace Gfx {
|
namespace Gfx {
|
||||||
|
|
||||||
|
@ -159,6 +160,43 @@ static Optional<Color> parse_rgb_color(const StringView& string)
|
||||||
return Color(r, g, b);
|
return Color(r, g, b);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
static Optional<Color> parse_rgba_color(const StringView& string)
|
||||||
|
{
|
||||||
|
ASSERT(string.starts_with("rgba("));
|
||||||
|
ASSERT(string.ends_with(")"));
|
||||||
|
|
||||||
|
auto substring = string.substring_view(5, string.length() - 6);
|
||||||
|
auto parts = substring.split_view(',');
|
||||||
|
|
||||||
|
if (parts.size() != 4)
|
||||||
|
return {};
|
||||||
|
|
||||||
|
bool ok;
|
||||||
|
auto r = parts[0].to_int(ok);
|
||||||
|
if (!ok)
|
||||||
|
return {};
|
||||||
|
auto g = parts[1].to_int(ok);
|
||||||
|
if (!ok)
|
||||||
|
return {};
|
||||||
|
auto b = parts[2].to_int(ok);
|
||||||
|
if (!ok)
|
||||||
|
return {};
|
||||||
|
|
||||||
|
double alpha = strtod(String(parts[3]).characters(), nullptr);
|
||||||
|
int a = alpha * 255;
|
||||||
|
|
||||||
|
if (r < 0 || r > 255)
|
||||||
|
return {};
|
||||||
|
if (g < 0 || g > 255)
|
||||||
|
return {};
|
||||||
|
if (b < 0 || b > 255)
|
||||||
|
return {};
|
||||||
|
if (a < 0 || a > 255)
|
||||||
|
return {};
|
||||||
|
|
||||||
|
return Color(r, g, b, a);
|
||||||
|
}
|
||||||
|
|
||||||
Optional<Color> Color::from_string(const StringView& string)
|
Optional<Color> Color::from_string(const StringView& string)
|
||||||
{
|
{
|
||||||
if (string.is_empty())
|
if (string.is_empty())
|
||||||
|
@ -334,6 +372,9 @@ Optional<Color> Color::from_string(const StringView& string)
|
||||||
if (string.starts_with("rgb(") && string.ends_with(")"))
|
if (string.starts_with("rgb(") && string.ends_with(")"))
|
||||||
return parse_rgb_color(string);
|
return parse_rgb_color(string);
|
||||||
|
|
||||||
|
if (string.starts_with("rgba(") && string.ends_with(")"))
|
||||||
|
return parse_rgba_color(string);
|
||||||
|
|
||||||
if (string[0] != '#')
|
if (string[0] != '#')
|
||||||
return {};
|
return {};
|
||||||
|
|
||||||
|
|
Loading…
Add table
Add a link
Reference in a new issue