VanguardReMaster/client/Assets/Vanguard/Runtime/UI/CardImageService.cs

55 lines
1.8 KiB
C#

using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
namespace Vanguard.UI
{
/// <summary>
/// Загрузка настоящих артов по imageKey. Соглашение: спрайт лежит в
/// Assets/Vanguard/Resources/CardArt/{imageKey}.png. Пока файла нет —
/// используется процедурный CardArt. Позже этот же вход можно
/// перевести на Addressables без изменения экранов.
/// </summary>
public static class CardImageService
{
private const string ResourceFolder = "CardArt/";
private static readonly Dictionary<string, Sprite> Cache =
new Dictionary<string, Sprite>();
public static void Apply(Image target, string imageKey, Sprite fallback)
{
if (target == null)
return;
target.sprite = fallback;
target.color = Color.white;
target.preserveAspect = false;
if (string.IsNullOrWhiteSpace(imageKey))
return;
if (Cache.TryGetValue(imageKey, out var cached))
{
if (cached != null)
target.sprite = cached;
return;
}
var texture = Resources.Load<Texture2D>(ResourceFolder + imageKey);
if (texture == null)
{
Cache[imageKey] = null;
return;
}
var sprite = Sprite.Create(
texture,
new Rect(0f, 0f, texture.width, texture.height),
new Vector2(0.5f, 0.5f),
100f);
Cache[imageKey] = sprite;
target.sprite = sprite;
}
}
}