#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 { [ShowInInspector] private float rotiation; [ShowInInspector] private float2 scale; [ShowInInspector] private bool similarityCalc; [ShowInInspector] private bool needFillTransform; private Image m_previewImage; // 查找时调用 public void SetTransform(float rotiation, float2 scale, bool similarityCalc) { this.rotiation = rotiation; this.scale = scale; this.similarityCalc = similarityCalc; this.needFillTransform = true; } private 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); } } protected override void OnApplyData(Image ui) { ApplyTransform(ui.transform); if (ElementInfo.HaveSlice) { ui.type = Image.Type.Sliced; } } public override void InitPreview() { if (ElementInfo == null) return; if (!TryGetComponent(out m_previewImage)) { m_previewImage = gameObject.AddComponent(); } LoadImageFromFile(ElementInfo.imgPath); ApplyTransform(transform); } 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(); 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