From acea7b2e728787a0d83bbf83c8c1f042d2c32e7e Mon Sep 17 00:00:00 2001 From: chai <215380520@qq.com> Date: Mon, 3 Jun 2024 10:15:45 +0800 Subject: + plugins project --- .../Serialization/SkinJsonConverter.cs | 57 ++++++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100644 Plugins/MonoGame.Extended/source/MonoGame.Extended.Gui/Serialization/SkinJsonConverter.cs (limited to 'Plugins/MonoGame.Extended/source/MonoGame.Extended.Gui/Serialization/SkinJsonConverter.cs') diff --git a/Plugins/MonoGame.Extended/source/MonoGame.Extended.Gui/Serialization/SkinJsonConverter.cs b/Plugins/MonoGame.Extended/source/MonoGame.Extended.Gui/Serialization/SkinJsonConverter.cs new file mode 100644 index 0000000..016ea6d --- /dev/null +++ b/Plugins/MonoGame.Extended/source/MonoGame.Extended.Gui/Serialization/SkinJsonConverter.cs @@ -0,0 +1,57 @@ +using System; +using System.Text.Json; +using System.Text.Json.Serialization; +using Microsoft.Xna.Framework; +using Microsoft.Xna.Framework.Content; + +namespace MonoGame.Extended.Gui.Serialization; + +public interface IGuiSkinService +{ + Skin Skin { get; set; } +} + +public class SkinService : IGuiSkinService +{ + public Skin Skin { get; set; } +} + +public class SkinJsonConverter : JsonConverter +{ + private readonly ContentManager _contentManager; + private readonly IGuiSkinService _skinService; + private readonly Type[] _customControlTypes; + + public SkinJsonConverter(ContentManager contentManager, IGuiSkinService skinService, params Type[] customControlTypes) + { + _contentManager = contentManager; + _skinService = skinService; + _customControlTypes = customControlTypes; + } + + /// + public override bool CanConvert(Type typeToConvert) => typeToConvert == typeof(Skin); + + /// + public override Skin Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + if (reader.TokenType == JsonTokenType.String) + { + var assetName = reader.GetString(); + + // TODO: Load this using the ContentManager instead. + using (var stream = TitleContainer.OpenStream(assetName)) + { + var skin = Skin.FromStream(_contentManager, stream, _customControlTypes); + _skinService.Skin = skin; + return skin; + } + + } + + throw new InvalidOperationException($"{nameof(SkinJsonConverter)} can only convert from a string"); + } + + /// + public override void Write(Utf8JsonWriter writer, Skin value, JsonSerializerOptions options) { } +} -- cgit v1.1-26-g67d0