Unity Texture2D 改变形状

记录一下,方便后面取用

private Texture2D TextureJuXingToFangXing(Texture2D tex)
    {
        if (tex.width == tex.height) return tex;

        int max = tex.height > tex.width ? tex.height : tex.width;
        int min = tex.height > tex.width ? tex.width : tex.height;
        int chaZhi = max - min;
        // 这里我也不知道为什么要用false
        Texture2D newTex = new Texture2D(max, max, tex.format, false); 

        Color[] oldColors = tex.GetPixels();

        // 取这个透明度不知道有没有用
        float a = oldColors[0].a;
        Color c = new Color(1, 1, 1, a);

        List<Color> listColor = new List<Color>();
        // 假如图片10*10 左下为(0,0) 右上为(9,9) 
        // Texture2d 的颜色排列方式 ( tex.GetPixels() 颜色数组的排列方式 ):
        // (0,0) (0,1) ... (0,9) (1,0) ...(9,8) (9,9)

        // 当原图片 宽度大于高度 需要在原图上面和下面补充颜色
        // 在 颜色数组前面添加 原图下面的颜色数量 
        // 在 数组后面添加上面的颜色数量即可
        if (tex.width > tex.height)
        {
            // 如果差值是奇数,默认下边和右边 多1
            int downPx = chaZhi / 2 + chaZhi % 2;
            int topPx = chaZhi - downPx;
            for (int i = 0; i < downPx * tex.width; i++)
            {
                listColor.Add(c);
            }
            for (int i = 0; i < oldColors.Length; i++)
            {
                listColor.Add(oldColors[i]);
            }
            for (int i = 0; i < topPx * tex.width; i++)
            {
                listColor.Add(c);
            }
        }
        // 当原图片 高度大于宽度 需要在原图左右补充颜色
        // 按照排列方式 把图片像素颜色 按照行来划分 
        // 每一行的颜色为 左边添加的颜色 原图这一行的颜色 右边添加的颜色
        else
        {
            int rightPx = chaZhi / 2 + chaZhi % 2;
            int leftPx = chaZhi - rightPx;
            for (int i = 0; i < max; i++)
            {
                for (int j = 0; j < leftPx; j++)
                {
                    listColor.Add(c);
                }
                for (int j = 0; j < tex.width; j++)
                {
                    listColor.Add(oldColors[i * tex.width + j]);
                }
                for (int j = 0; j < rightPx; j++)
                {
                    listColor.Add(c);
                }
            }
        }
        newTex.SetPixels(listColor.ToArray());
        newTex.Apply();
        return newTex;
    }
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值