com.soviby.unity.ui.ugui-to.../Assets/Editor/Entity/ImageEntity.cs

105 lines
3.3 KiB
C#

#if UNITY_EDITOR
using Sirenix.OdinInspector;
using UguiToolkit.Editor;
using Unity.Mathematics;
using UnityEditor;
using UnityEngine;
using UnityEngine.UI;
namespace UguiToolkit.Editor
{
public class ImageEntity : BaseEntity<Image, LayoutInfo.ImageInfo>
{
[ShowInInspector]
private float rotiation;
[ShowInInspector]
private float2 scale;
[ShowInInspector]
private bool similarityCalc;
[ShowInInspector]
private bool needFillTransform;
private Image m_previewImage;
protected override void OnApplyData(Image ui)
{
ApplyTransform(ui.transform);
}
public void InitPreviewImage()
{
if (ElementInfo == null) return;
if (!TryGetComponent<Image>(out m_previewImage))
{
m_previewImage = gameObject.AddComponent<Image>();
}
LoadImageFromFile(ElementInfo.imgPath);
ApplyTransform(transform);
}
void LoadImageFromFile(string path)
{
if (System.IO.File.Exists(path))
{
byte[] fileData = System.IO.File.ReadAllBytes(path);
Texture2D texture = new Texture2D(2, 2);
texture.LoadImage(fileData); // 加载图片数据到Texture2D
Sprite sprite = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), new Vector2(0.5f, 0.5f));
m_previewImage.sprite = sprite;
m_previewImage.color = new Color(1, 1, 1, 0.7f);
m_previewImage.SetNativeSize();
}
else
{
Debug.LogError("File not found at path: " + path);
}
}
// 查找时调用
public void SetTransform(float rotiation, float2 scale, bool similarityCalc)
{
this.rotiation = rotiation;
this.scale = scale;
this.similarityCalc = similarityCalc;
this.needFillTransform = true;
}
// 查找时调用
public void ClearFillTransform() => this.needFillTransform = false;
public override void ApplyTransform(Transform tf)
{
if (needFillTransform)
{
if (similarityCalc)
{
var rt = tf as RectTransform;
rt.anchorMax = rt.anchorMin;
rt.sizeDelta = new Vector2(ElementInfo.w, ElementInfo.h);
rt.rotation = Quaternion.identity;
}
else
{
var rt = tf as RectTransform;
// 设置中心点为0.5 0.5
rt.pivot = new Vector2(0.5f, 0.5f);
rt.rotation = Quaternion.Euler(0, 0, rotiation * -1);
// size
var img = tf.GetComponent<Image>();
img.SetNativeSize();
rt.anchorMax = rt.anchorMin;
rt.sizeDelta = new Vector2(rt.sizeDelta.x * scale.x, rt.sizeDelta.y * scale.y);
}
}
var position = ElementInfo.Position;
tf.position = StageManager.Instance.PrefabContentsRoot.transform.TransformPoint(new Vector3(position.x, position.y, 0));
}
}
}
#endif