Search Unity

How to display the central part of a texture on the viewport?

Discussion in 'Shaders' started by zyjisdog, Oct 16, 2019.

  1. zyjisdog

    zyjisdog

    Joined:
    Oct 16, 2019
    Posts:
    7
    I'm trying to show a central part of the texture on the viewport.
    For example, this texture (which size is larger than viewport) below:
    1920x1080_TEASER_CP77.jpg
    I want to show the center part (about 1/4 size) on the full viewport:
    center.png

    So I wrote a shader to do this:
    Code (CSharp):
    1. UNITY_DECLARE_TEX2D(_RealWorldTex);
    2. ...
    3. half4 _RealWorldTex_TexelSize;
    4. ...
    5. fixed4 frag(v2f i) : SV_Target
    6.             {
    7.                 float2 offset = ((_RealWorldTex_TexelSize.z - _MainTex_TexelSize.z) * 0.5,
    8.                                  (_RealWorldTex_TexelSize.w - _MainTex_TexelSize.w) * 0.5);
    9.                 fixed4 realWorldTex = _RealWorldTex.Load(int3((i.uv * _RealWorldTex_TexelSize.zw + offset), 0));
    10.                 ...
    11.             }
    12.  
    But it didn't work as I expected:
    result.png

    It didn't show the central part of the texture on the full viewport.

    Shader code was inspired by bgolus from https://forum.unity.com/threads/what-is-glsls-texelfetch-in-unitys-unlit-shader.639757/
     
    Last edited: Oct 16, 2019
  2. Olmi

    Olmi

    Joined:
    Nov 29, 2012
    Posts:
    1,553
    Hi,
    I think this should do the trick (from my notes):

    Code (CSharp):
    1. // Offset UV so that it begins from center of the image
    2. i.uv -= 0.5;
    3. // Scale it
    4. i.uv *= _Scale;
    5. // Move it back to center
    6. i.uv += 0.5;
    7. // sample the texture
    8. fixed4 col = tex2D(_MainTex, i.uv);
    So you move that 0-1 UV space so that it's origin is in the center of the image, then scale and move back.

    EDIT: Tried it, work fine (scales from center). But you have to of course provide correct scale factor to get the desired image cropping.

    Either generate the scaling values by calculating them or use some list of predefined values...
     
    Last edited: Oct 16, 2019
  3. zyjisdog

    zyjisdog

    Joined:
    Oct 16, 2019
    Posts:
    7
    Thanks Olmi, tex2D() works fine with me.