Unity3D中texture2D函式使用詳解
在Unity3D中可以使用指令碼建立texture2D貼圖,並對畫素進行操作。
對Texture2D畫素操作後,一定要Apply
for (int i = 0; i < 100; i++) { for (int j = 0; j < 500; j++) { m_Texture2D.SetPixel(i, j, Color.white); } } m_Texture2D.Apply(); m_Image.sprite = Sprite.Create(m_Texture2D, new Rect(0,0,m_Texture2D.width, m_Texture2D.height), Vector2.one); Debug.Log(m_Texture2D.GetPixel(0, 0));
建構函式
Texture2D(int width,
int height);
Texture2D(int width,
int height, TextureFormat format,
bool mipmap);
Texture2D(int width,
int height, TextureFormat format,
bool mipmap, bool linear);
方法
對畫素的操作
1.獲取畫素顏色
Color GetPixel(int x, int y);
Returns pixel color at coordinates (x, y).
2.獲取正交化座標系下畫素顏色
Color GetPixelBilinear(float u, float v);
Returns filtered pixel color at normalized coordinates (u, v).
多用於處理得知多邊形UV座標時對畫素的處理
3.獲取一個區塊的畫素顏色
Color[] GetPixels(int miplevel = 0);
Get a block of pixel colors.
獲取以x,y 為起始點,大小為width,height的一個區塊,
返回的是一個數組,陣列內顏色的點順序為從左至右,從下至上
4.獲取(指定mipmap level級別)的整張貼圖的畫素顏色(使用Color32格式)
Color32[] GetPixels32(int miplevel = 0);
Get a block of pixel colors in Color32 format.
讀取速度比反覆使用getPixel讀取速度快
5.設定畫素顏色
void SetPixel(int x, int y, Color color);
Sets pixel color at coordinates (x,y).
6.設定(指定mipmap level級別)的整張貼圖的畫素顏色
void SetPixels(Color[] colors, int miplevel = 0);
Set a block of pixel colors.
設定指定mipmap level下的整張貼圖顏色
7.設定(指定mipmap level級別)的整張貼圖的畫素顏色(使用Color32格式)
void SetPixels32(Color32[] colors, int miplevel = 0);
Set a block of pixel colors.
對貼圖的操作
1.當對貼圖的畫素操作後必須呼叫的函式,使操作生效。
void Apply(bool updateMipmaps = true, bool makeNoLongerReadable = false);
Actually apply all previous SetPixel and SetPixels changes.
2.將貼圖壓縮成DXT格式
void Compress(bool highQuality);
Compress texture into DXT format.
3.將貼圖轉碼為PNG格式
byte[] EncodeToPNG();
Encodes this texture into PNG format.
4.載入一張貼圖
bool LoadImage(byte[] data);
Loads an image from a byte array.
可以載入的格式為:JPG,PNG
5.將多張貼圖打包到一張圖集中
Rect[] PackTextures(Texture2D[] textures, int padding, int maximumAtlasSize = 2048, bool makeNoLongerReadable = false);
Packs multiple Textures into a texture atlas.
6.將螢幕色讀入到貼圖
void ReadPixels(Rect source, int destX, int destY, bool recalculateMipMaps = true);
Read screen pixels into the saved texture data.
rect source 可以用來建立需要擷取的螢幕區域,
destX,destY 表明了渲染到貼圖的起始點,(0,0)點為螢幕的左下角。
readPixels函式主要可以配合camera.OnPostRender進行截圖及RenderToTexture操作,
7.重新定義貼圖
bool Resize(int width, int height, TextureFormat format, bool hasMipMap);
Resizes the texture.