|
2 | 2 | using System.Numerics; |
3 | 3 | using System.Runtime.CompilerServices; |
4 | 4 | using System.Runtime.InteropServices; |
| 5 | +using System.Text.Json; |
| 6 | +using System.Text.Json.Serialization; |
5 | 7 |
|
6 | 8 | namespace Foster.Framework; |
7 | 9 |
|
8 | 10 | /// <summary> |
9 | 11 | /// 8-bit RGBA Color struct |
10 | 12 | /// </summary> |
11 | | -[StructLayout(LayoutKind.Sequential, Pack = 4, Size = 4)] |
| 13 | +[StructLayout(LayoutKind.Sequential, Pack = 4, Size = 4), JsonConverter(typeof(JsonConverter))] |
12 | 14 | public struct Color : IEquatable<Color> |
13 | 15 | { |
14 | 16 | public static readonly Color Transparent = new(0, 0, 0, 0); |
@@ -316,4 +318,17 @@ public static Color Lerp(Color a, Color b, float amount) |
316 | 318 | public static implicit operator Color(Vector3 vec) => new Color(vec.X, vec.Y, vec.Z, 1.0f); |
317 | 319 | public static implicit operator Vector4(Color col) => col.ToVector4(); |
318 | 320 | 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 | + } |
319 | 334 | } |
0 commit comments