Unity图像自适应按原本比例等比缩放

在项目开发过程中遇到了需要将动态加载的图像按原本比例展示在固定大小的UI区域内的需求,特此记录一下:

 public RawImage imagePhoto;


   /// <summary>
    /// 设置图片纹理
    /// </summary>
    /// <param name="texturePhoto"></param>
 public void SetPopPiece(Texture texturePhoto)
 {
    //先设定texture 纹理
    imagePhoto.texture = TextureToTexture2D(texturePhoto);
    //再将需要设定的image,和展示区域的宽和高转入缩放方法
    ZoomImage(imagePhoto, imagePhoto.transform.parent.GetComponent<RectTransform>().sizeDelta.y, imagePhoto.transform.parent.GetComponent<RectTransform>().sizeDelta.x-40);
}

   /// <summary>
    /// 纹理转换
    /// </summary>
    /// <param name="texture"></param>
 private Texture2D TextureToTexture2D(Texture texture)
    {
        Texture2D texture2D = new Texture2D(texture.width, texture.height, TextureFormat.RGBA32, false);
        RenderTexture currentRT = RenderTexture.active;
        RenderTexture renderTexture = RenderTexture.GetTemporary(texture.width, texture.height, 32);
        Graphics.Blit(texture, renderTexture);

        RenderTexture.active = renderTexture;
        texture2D.ReadPixels(new Rect(0, 0, renderTexture.width, renderTexture.height), 0, 0);
        texture2D.Apply();

        RenderTexture.active = currentRT;
        RenderTexture.ReleaseTemporary(renderTexture);

        return texture2D;
    }
  /// <summary>
    /// 缩放图片
    /// </summary>
    /// <param name="image"></param>
    /// <param name="destHeight"></param>
    /// <param name="destWidth"></param>
    public void ZoomImage(RawImage image, float destHeight, float destWidth)
    {
        image.SetNativeSize();//先将图片还原到原大小


        float width = 0, height = 0;
        //按比例缩放
        var sizeDelta = image.GetComponent<RectTransform>().sizeDelta;
        float sourWidth = sizeDelta.x;
        float sourHeight = sizeDelta.y;

        //if (sourHeight > destHeight || sourWidth > destWidth)
        //{


        //}
        //else
        //{
        //    width = sourWidth;
        //    height = sourHeight;
        //}

        if ((sourWidth * destHeight) > (sourHeight * destWidth))
        {
            width = destWidth;
            height = (destWidth * sourHeight) / sourWidth;
        }
        else
        {
            height = destHeight;
            width = (sourWidth * destHeight) / sourHeight;
        }
        image.GetComponent<RectTransform>().sizeDelta = new Vector2(width, height);
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值