mirror of
https://github.com/LadybirdBrowser/ladybird.git
synced 2024-11-22 15:40:19 +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
Notes:
sideshowbarker
2024-07-19 06:57:07 +09:00
Author: https://github.com/awesomekling Commit: https://github.com/SerenityOS/serenity/commit/b7339745d0f
1 changed files with 41 additions and 0 deletions
|
@ -34,6 +34,7 @@
|
|||
#include <LibIPC/Decoder.h>
|
||||
#include <ctype.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
|
||||
namespace Gfx {
|
||||
|
||||
|
@ -159,6 +160,43 @@ static Optional<Color> parse_rgb_color(const StringView& string)
|
|||
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)
|
||||
{
|
||||
if (string.is_empty())
|
||||
|
@ -334,6 +372,9 @@ Optional<Color> Color::from_string(const StringView& string)
|
|||
if (string.starts_with("rgb(") && string.ends_with(")"))
|
||||
return parse_rgb_color(string);
|
||||
|
||||
if (string.starts_with("rgba(") && string.ends_with(")"))
|
||||
return parse_rgba_color(string);
|
||||
|
||||
if (string[0] != '#')
|
||||
return {};
|
||||
|
||||
|
|
Loading…
Reference in a new issue