先上代码
using System.IO;
using System.Collections;
using UnityEngine;
using UnityEngine.UI;
using System;
public class Test3 : MonoBehaviour
{
public RawImage image;
public Texture2D te;
public Texture2D texture;
void Update()
{
if (Input.GetKeyDown(KeyCode.A))
{
image.texture = AmendAtlas(new UnityEngine.Vector2(0,1536),new UnityEngine.Vector2(512,512),te,texture);
}
}
/// <summary>
/// 修改图集
/// </summary>
public Texture2D AmendAtlas(UnityEngine.Vector2 _修改图片的起始点, UnityEngine.Vector2 _修改图集的范围,Texture2D _图集,Texture2D _要添加的图片)
{
Color[] colors = _图集.GetPixels();
Texture2D texture2D = new Texture2D(_图集.width, _图集.height);
texture2D.SetPixels(colors);
texture2D.SetPixels((int)_修改图片的起始点.x, (int)_修改图片的起始点.y, (int)_修改图集的范围.x, (int)_修改图集的范围.y, _要添加的图片.GetPixels());
texture2D.Apply();
return texture2D;
}
/// <summary>
/// 图片压缩
/// </summary>
/// <param name="tex"></param>
/// <param name="width"></param>
/// <param name="height"></param>
/// <returns></returns>
public Texture2D ReSetTextureSize(Texture2D tex, int width, int height)
{
var rendTex = new RenderTexture(width, height, 24, RenderTextureFormat.ARGB32);
rendTex.Create();
Graphics.SetRenderTarget(rendTex);
GL.PushMatrix();
GL.Clear(true, true, Color.clear);
GL.PopMatrix();
var mat = new Material(Shader.Find("Unlit/Transparent"));
mat.mainTexture = tex;
Graphics.SetRenderTarget(rendTex);
GL.PushMatrix();
GL.LoadOrtho();
mat.SetPass(0);
GL.Begin(GL.QUADS);
GL.TexCoord2(0, 0);
GL.Vertex3(0, 0, 0);
GL.TexCoord2(0, 1);
GL.Vertex3(0, 1, 0);
GL.TexCoord2(1, 1);
GL.Vertex3(1, 1, 0);
GL.TexCoord2(1, 0);
GL.Vertex3(1, 0, 0);
GL.End();
GL.PopMatrix();
var finalTex = new Texture2D(rendTex.width, rendTex.height, TextureFormat.ARGB32, false);
RenderTexture.active = rendTex;
finalTex.ReadPixels(new Rect(0, 0, finalTex.width, finalTex.height), 0, 0);
finalTex.Apply();
return finalTex;
}
public void writeCaptureDataToFile(Texture2D texture, string dataPath, string filename)
{
string path_full =Path.Combine(dataPath,filename+".jpg");
// 存入jpg文件
StartCoroutine(saveTexture2DtoFile(texture, path_full));
}
// 保存图片到指定目录
private IEnumerator saveTexture2DtoFile(Texture2D texture, string path, Action<object> callback=null)
{
//等待渲染线程结束
yield return new WaitForEndOfFrame();
byte[] textureData = texture.EncodeToJPG();
System.IO.File.WriteAllBytes(path, textureData);
callback?.Invoke(null);
Debug.Log("图片文件写入完毕:" + path);
}
}
这图集大小为 1024 * 2048
修改红色框住的部分 并填补
该区域大小为 512 * 512
起始点为该区域的左下角 位置为 (0,1536)
填入数据
然后运行代码
得到下面的结果
Over