在Unity5中缩放PNG? - Bountie

时间:2016-03-01 02:13:17

标签: unity3d unity5 unity5.3 unity3d-ui

令人惊讶的是,在Unity中,多年来唯一的方法简单地扩展实际的PNG 就是使用非常棒的库http://wiki.unity3d.com/index.php/TextureScale

以下示例

如何使用Unity5功能缩放PNG?现在必须有一种新的用户界面等等。

因此,缩放实际像素(例如Color[])或字面上的PNG文件,可能是从网上下载的。

(顺便说一下,如果你是Unity的新手,Resize调用是无关的。它只会改变数组的大小。)

public WebCamTexture wct;

public void UseFamousLibraryToScale()
    {
    // take the photo. scale down to 256
    // also  crop to a central-square

    WebCamTexture wct;
    int oldW = wct.width; // NOTE example code assumes wider than high
    int oldH = wct.height;

    Texture2D photo = new Texture2D(oldW, oldH,
          TextureFormat.ARGB32, false);
    //consider WaitForEndOfFrame() before GetPixels
    photo.SetPixels( 0,0,oldW,oldH, wct.GetPixels() );
    photo.Apply();

    int newH = 256;
    int newW = Mathf.FloorToInt(
           ((float)newH/(float)oldH) * oldW );

    // use a famous Unity library to scale
    TextureScale.Bilinear(photo, newW,newH);

    // crop to central square 256.256
    int startAcross = (newW - 256)/2;
    Color[] pix = photo.GetPixels(startAcross,0, 256,256);
    photo = new Texture2D(256,256, TextureFormat.ARGB32, false);
    photo.SetPixels(pix);
    photo.Apply();
    demoImage.texture = photo;

    // consider WriteAllBytes(
    //   Application.persistentDataPath+"p.png",
    //   photo.EncodeToPNG()); etc
    }

只是BTW它发生在我身上我可能只是在谈论缩小这里(因为你经常需要发布图像,动态创建或其他任何东西。)我想,通常不会有需要扩大图像尺寸;这是毫无意义的质量。

Bounty即将到来!

1 个答案:

答案 0 :(得分:4)

如果你可以使用拉伸缩放,那么使用临时的RenderTexture和Graphics.Blit实际上有更简单的方法。如果你需要它是Texture2D,暂时交换RenderTexture.active并将其像素读取到Texture2D就可以了。例如:

public Texture2D ScaleTexture(Texture src, int width, int height){
    RenderTexture rt = RenderTexture.GetTemporary(width, height);
    Graphics.Blit(src, rt);

    RenderTexture currentActiveRT = RenderTexture.active;
    RenderTexture.active = rt;
    Texture2D tex = new Texture2D(rt.width,rt.height); 

    tex.ReadPixels(new Rect(0, 0, tex.width, tex.height), 0, 0);
    tex.Apply();

    RenderTexture.ReleaseTemporary(rt);
    RenderTexture.active = currentActiveRT;

    return tex;
}