using System.Collections;
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEngine;
using UnityEngine.UI;

public class imageGradationView : MonoBehaviour
{
    public Color color1 = Color.black;
    public Color color2 = Color.white;
    // Start is called before the first frame update
    private Color[] allColor = null;
    private Texture2D texture2D = null;
    private int angle = 90;//仅支持90#  0 左到右 180 右到左 90 上到下 270 下到上，其他方向暂时不支持
    
    void Start()
    {
        initMember();
    }
    void initMember()
    {
        if(allColor != null)
        {
            return;
        }
        RectTransform rectTransform = GetComponent<RectTransform>();
        texture2D = new Texture2D((int)rectTransform.rect.width,(int)rectTransform.rect.height,TextureFormat.RGBA32,false);
        Image image = GetComponent<Image>();
        if(image == null)
        {
            image = gameObject.AddComponent<Image>();
        }
        image.sprite = image.sprite = Sprite.Create(texture2D, new Rect(0, 0, texture2D.width, texture2D.height), new Vector2(0.5f, 0.5f));
        allColor = new Color[texture2D.width * texture2D.height]; //texture2D.GetPixels();
        updateImageView();
        texture2D.SetPixels(allColor);
        texture2D.Apply();
    }
    void updateImageView()
    {
        if (angle.Equals(90))
        {
            float height = texture2D.height;
            float[] diffValue = { (color1.r - color2.r)/height, (color1.g - color2.g) / height , (color1.b - color2.b) / height , (color1.a - color2.a) / height };
            for (int y = 0; y < texture2D.height; y++)
            {
                Color lineColor = new Color(color2.r + diffValue[0] * y, color2.g + diffValue[1] * y, color2.b + diffValue[2] * y, color2.a + diffValue[3] * y);
                for(int x = 0;x < texture2D.width; x++)
                {
                    int idx = y * texture2D.width + x;
                    allColor[idx] = lineColor;
                }
            }
        }
    }
    // Update is called once per frame
    void Update()
    {
        initMember();
    }
}
