NVentimiglia / Unity3d-Databinding-Mvvm-Mvc

Unity3d uGUI Observable library for Mvvm / Mvc
http://unity3dfoundation.com
63 stars 16 forks source link

ImageBinder should also accept Sprite #9

Closed negue closed 9 years ago

NVentimiglia commented 9 years ago

Thanks.

This should fix it. I will test / push later.

NVentimiglia commented 9 years ago
using Foundation.Databinding.View;
using UnityEngine;
using UnityEngine.UI;

namespace Foundation.Databinding.Components
{
    /// <summary>
    /// UI.Image to Texture2d or Color
    /// </summary>
    [RequireComponent(typeof(Image))]
    [AddComponentMenu("Foundation/Databinding/ImageBinder")]
    public class ImageBinder : BindingBase
    {
        protected Image Target;

        [HideInInspector]
        public BindingInfo SpriteBinding = new BindingInfo { BindingName = "Sprite" };
        [HideInInspector]
        public BindingInfo ColorBinding = new BindingInfo { BindingName = "Color" };

        protected bool IsInit;
        protected Sprite original = null;

        protected void Awake()
        {
            Init();
        }

        public override void Init()
        {
            if (IsInit)
                return;
            IsInit = true;

            Target = GetComponent<Image>();

            original = Target.sprite;

            SpriteBinding.Action = UpdateLabel;
            SpriteBinding.Filters = BindingFilter.Properties;
            SpriteBinding.FilterTypes = new[] { typeof(Texture2D), typeof(Sprite) };

            ColorBinding.Action = UpdateColor;
            ColorBinding.Filters = BindingFilter.Properties;
            ColorBinding.FilterTypes = new[] { typeof(Color) };
        }

        private void UpdateLabel(object arg)
        {
            if (Target)
            {
                if (arg is Sprite)
                {
                    Target.sprite = (Sprite)arg;
                }
                else if(arg is Texture2D)
                {
                    var texture = arg as Texture2D;
                    Target.sprite = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), Vector2.zero);
                }
                else
                {
                    Target.sprite = original;
                }
            }
        }

        private void UpdateColor(object arg)
        {
            if (Target)
            {
                Target.color = ((Color)arg);
            }
        }
    }
}
negue commented 9 years ago

Thanks it worked! :smiley:

NVentimiglia commented 9 years ago

Cured int 36d870887cbb3a0e33bef478d86b4314a008f6c3