using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
#if UNITY_EDITOR
using UnityEditor;
#endif
[DisallowMultipleComponent]
[RequireComponent(typeof(RectTransform))]
[RequireComponent(typeof(CanvasRenderer))]
[ExecuteInEditMode]//运行时可取消注释
public class MyImage : Image
{
public float wide;
public float height;
public Vector3 t1;
protected override void OnPopulateMesh(VertexHelper toFill)
{
base.OnPopulateMesh(toFill);
//想要绘制出看得见的图片 uv要对应上
// uv中的每一项和vertices中的每一项都是一一对应的
//https://blog.youkuaiyun.com/jk823394954/article/details/53870779
//在unity中,UV坐标划分,分下面两大步骤
//1.参考的标准是,unity刚导入时的那张图,即原图
//2.原图的左下角uv坐标定为(0, 0),原图的右上角的uv坐标定位(1, 1),
//原图的其它任何一个位置按照比例都会有一个uv坐标,比如原图的左上角的uv坐标定位(0,1),
//原图的右下角的UV坐标定位(1,0),原图的中心(对角线的交点)位置为(0.5,0.5),等等
//再次强调,uv中的每一项和vertices中的每一项都是一一对应的,
// unity在贴图的时候,会把uv中每一个点和vertices中对应索引的顶点一一关联起来,这样可以实现贴图任意形状显示
//实现效果Image任意形状完全显示
//延申如何实现UGUIImage360度填充方式显示 移动顶点的方式
wide = gameObject.GetComponent<RectTransform>().rect.width / 2;
height = gameObject.GetComponent<RectTransform>().rect.height / 2;
toFill.Clear();
//自己绘制所需控制的顶点
toFill.AddVert(Vector3.zero, color, new Vector2(0.5f, 0.5f));//0
toFill.AddVert(new Vector3(wide, height, 0), color, new Vector2(1f, 1f));//1
toFill.AddVert(new Vector3(wide, -height, 0), color, new Vector2(1f, 0f));//2
toFill.AddVert(new Vector3(-wide, -height, 0), color, new Vector2(0f, 0f));//3
toFill.AddVert(new Vector3(-wide, height, 0), color, new Vector2(0f, 1f));//4
//绘制图形
toFill.AddTriangle(0, 1, 2);
toFill.AddTriangle(0, 2, 3);
toFill.AddTriangle(0, 3, 4);
toFill.AddTriangle(0, 4, 1);
//修改顶点1的位置以达到改变图片形状
UIVertex vertex = new UIVertex();
toFill.PopulateUIVertex(ref vertex, 1);//获取指定索引顶点数据 包含顶点颜色,顶点坐标,以及顶点
vertex.position = t1;
toFill.SetUIVertex(vertex, 1);//设置一个顶点的数据
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[ExecuteInEditMode]//运行时可取消注释
public class Controller : MonoBehaviour
{
public MyImage myImage;
// Start is called before the first frame update
void Start()
{
transform.parent = myImage.transform;
GetComponent<RectTransform>().anchoredPosition3D = new Vector3(myImage.wide,myImage.height,0);
}
// Update is called once per frame
void Update()
{
myImage.t1 = GetComponent<RectTransform>().anchoredPosition3D;
myImage.SetAllDirty();
}
}