Unity 3D : Texture2D 縮放大小

方法一 :

Texture2D ScaleTexture(Texture2D source, float targetWidth, float targetHeight)
{
       Texture2D result = new Texture2D((int)targetWidth, (int)targetHeight, source.format, false);

       float incX = (1.0f / targetWidth);
       float incY = (1.0f / targetHeight);

       for (int i = 0; i < result.height; ++i)
       {
           for (int j = 0; j < result.width; ++j)
           {
               Color newColor = source.GetPixelBilinear((float)j / (float)result.width, (float)i / (float)result.height);
               result.SetPixel(j, i, newColor);
           }
       }

       result.Apply();
       return result;
}

方法二 ( GPU )

原始圖像大小除以 divideSize = 新圖像大小,如果 divideSize = 2,那麼新圖像將會縮小為原來的四分之一 ( 長寬各除以 2 )

C # :

RenderTexture Resize(ComputeShader shader, int divideSize) {
        RenderTexture t = new RenderTexture(inputTexture.width/ divideSize, inputTexture.height / divideSize, 24, RenderTextureFormat.ARGBFloat);
        t.enableRandomWrite = true;
        t.Create();
        int k = shader.FindKernel("Resize");
        shader.SetInt("divideSize", divideSize);        
        shader.SetTexture(k, "inputTexture", inputTexture);
        shader.SetTexture(k, "outputTexture", t);
        shader.Dispatch(k, inputTexture.width / 8, inputTexture.height / 8, 1);
        return t;
}

Compute Shader :

#pragma kernel Resize

int divideSize; // 原始圖像大小除以這個值
Texture2D inputTexture;
RWTexture2D <float4> outputTexture;

[numthreads(8, 8, 1)]
void Resize(uint3 id : SV_DispatchThreadID) 
{
	outputTexture[id.xy / divideSize] = inputTexture[id.xy];
}
  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值