// --------------------------------------------------------------------------------------------------------------------
//
// Copyright (c) VRMADA, All rights reserved.
//
// --------------------------------------------------------------------------------------------------------------------
using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using UltimateXR.Extensions.System.IO;
using UnityEngine;
using UnityEngine.UI;
namespace UltimateXR.Extensions.Unity.Render
{
///
/// extensions.
///
public static class SpriteExt
{
#region Public Methods
///
/// Creates a sprite, for a given using a .
///
/// Image component the sprite will be used for
/// Texture
/// Loaded sprite
public static Sprite FromTexture(Image targetImage, Texture2D texture2D)
{
RectTransform t = targetImage.rectTransform;
Vector2 size = t.sizeDelta;
Rect rect = new Rect(0.0f, 0.0f, size.x, size.y);
return Sprite.Create(texture2D, rect, t.pivot);
}
///
/// Loads asynchronously a sprite from a given file . See for
/// information on the file location.
///
/// Image component the sprite will be used for
/// File location. for more information
/// Optional cancellation token, to cancel the operation.
/// An awaitable that returns the loaded sprite
/// is null or empty
/// Task canceled using
/// The file specified in was not found.
/// is in an invalid format.
/// An I/O error occurred while opening the file.
/// The stream is currently in use by a previous read operation.
public static async Task ReadSpriteFileAsync(Image targetImage, string uri, CancellationToken ct = default)
{
Texture2D texture2D = await Texture2DExt.FromFile(uri, ct);
RectTransform t = targetImage.rectTransform;
Vector2 size = t.sizeDelta;
Rect rect = new Rect(0.0f, 0.0f, size.x, size.y);
return Sprite.Create(texture2D, rect, t.pivot);
}
///
/// Loads asynchronously a sprite encoded in a base64 .
///
/// Image component the sprite will be used for
/// String encoding the file in base64
/// Optional cancellation token, to cancel the operation
/// An awaitable that returns the loaded sprite
/// is null or empty
/// Task canceled using
///
/// The length of , ignoring white-space characters, is not
/// zero or a multiple of 4.
///
public static async Task ReadSpriteBase64Async(Image targetImage, string base64, CancellationToken ct = default)
{
Texture2D texture2D = await Texture2DExt.FromBase64(base64, ct);
RectTransform t = targetImage.rectTransform;
Vector2 size = t.sizeDelta;
Rect rect = new Rect(0.0f, 0.0f, size.x, size.y);
return Sprite.Create(texture2D, rect, t.pivot);
}
#endregion
}
}