RectTransform、Texture2d 绽放问题

1、缩小一个Texture2d

代码:

/// <summary>
/// 缩小一个texture
/// </summary>
/// <param name="originTexture"></param>
/// <param name="rate"></param>
/// <returns></returns>
Texture2D CeateTexture_With_Scale(Texture2D originTexture, float rate)
{
    if (rate >= 1f)
    {
        return originTexture;
    }

    int with = (int)(originTexture.width * rate);
    int height = (int)(originTexture.height * rate);
    int count = with * height;
    Texture2D textrue = new Texture2D(with, height, TextureFormat.ARGB32, false);
    Color32[] originColors = originTexture.GetPixels32();
    Color32[] colors = new Color32[count];
    float _1_rate = 1 / rate;
    for (int y = 0; y < height; y++)
    {
        for (int x = 0; x < with; x++)
        {
            int i = x + y * with;
            int j = (int)(_1_rate * x) + (int)(_1_rate * y) * originTexture.width;
            colors[i] = originColors[j];
        }
    }
    textrue.SetPixels32(colors);
    textrue.Apply();

    return textrue;
}

2、缩放一个RawImage的UV,使用的它的Texture不变形

//[lzh]
using UnityEngine;
using UnityEngine.UI;
using System.Collections;

public class Test : MonoBehaviour
{
    public RawImage rawImg;
    public RectTransform rtRawImg;
    private Texture texture;

    // Use this for initialization
    void Start ()
    {
        texture = rawImg.texture;
        ScaleUV();
    }


    void ScaleUV()
    {
        Vector2 rtSize = rtRawImg.rect.size;
        Vector2 texSize = new Vector2(texture.width, texture.height);
        //Debug.Log(rtSize);

        float rateRt = rtSize.y / rtSize.x;
        float rateTex = texSize.y / texSize.x;

        float temp = rateTex / rateRt;
        Debug.Log(temp);
        if(temp<1)
        {
            //rawImg.uvRect.x = 0.5f * (temp - 1);

            rawImg.uvRect = new Rect(0.5f * (1-temp), 1f, temp, 1f);
        }
        else if(temp > 1)
        {
            temp = 1 / temp;
            rawImg.uvRect = new Rect(1f, 0.5f * (1 - temp),1f, temp);
        }

    }

}

你可能感兴趣的:(RectTransform、Texture2d 绽放问题)