unity实现Image任意形状完全显示

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.csdn.net/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();
    }
}

 

 

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值