在Unity5中如何缩放PNG图片?- Bountie

8
在Unity中,令人惊讶的是多年来唯一简单地缩放实际PNG的方法是使用非常棒的库http://wiki.unity3d.com/index.php/TextureScale
以下是示例:
如何使用Unity5函数缩放PNG?现在有新的UI等等,肯定有办法了。
因此,可以缩放实际像素(例如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
    }

顺便提一下,我可能只在谈论缩小图像的情况(因为你经常需要这样做才能发布图片,即兴创作等等)。我想,很少有必要将图像放大到更大的尺寸;这对于质量来说是没有意义的。


2
目前Unity还没有内置的方法来缩放PNG图片,Wiki上的代码是最好的方式,但如果需要更高级的操作,可以考虑集成devIL或freeimage来进行缩放或处理。 - Chris
1个回答

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;
}

老问题重新浮现了!太有趣了,我从未想过。不知道质量如何?我会试一下的。 - Fattie
哦,没看到日期 :p - dkrprasetya
别担心!我实际上已经加了一份赏金 - 也许你会默认赢得它 :) - Fattie

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接