Skip to content

Commit 0b471a9

Browse files
committed
Color Serialization
1 parent 20ddd2c commit 0b471a9

File tree

1 file changed

+16
-1
lines changed

1 file changed

+16
-1
lines changed

Framework/Images/Color.cs

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,13 +2,15 @@
22
using System.Numerics;
33
using System.Runtime.CompilerServices;
44
using System.Runtime.InteropServices;
5+
using System.Text.Json;
6+
using System.Text.Json.Serialization;
57

68
namespace Foster.Framework;
79

810
/// <summary>
911
/// 8-bit RGBA Color struct
1012
/// </summary>
11-
[StructLayout(LayoutKind.Sequential, Pack = 4, Size = 4)]
13+
[StructLayout(LayoutKind.Sequential, Pack = 4, Size = 4), JsonConverter(typeof(JsonConverter))]
1214
public struct Color : IEquatable<Color>
1315
{
1416
public static readonly Color Transparent = new(0, 0, 0, 0);
@@ -316,4 +318,17 @@ public static Color Lerp(Color a, Color b, float amount)
316318
public static implicit operator Color(Vector3 vec) => new Color(vec.X, vec.Y, vec.Z, 1.0f);
317319
public static implicit operator Vector4(Color col) => col.ToVector4();
318320
public static implicit operator Vector3(Color col) => col.ToVector3();
321+
322+
public class JsonConverter : JsonConverter<Color>
323+
{
324+
public override Color Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
325+
{
326+
if (reader.TokenType == JsonTokenType.String)
327+
return FromHexStringRGBA(reader.GetString() ?? string.Empty);
328+
return new();
329+
}
330+
331+
public override void Write(Utf8JsonWriter writer, Color value, JsonSerializerOptions options)
332+
=> writer.WriteStringValue(value.ToHexStringRGBA());
333+
}
319334
}

0 commit comments

Comments
 (0)