//需要一个摄像机
void BuildTexture ( ) {
Camera camera = Camera.main;
//尺寸
Rect rect = new Rect(0, 0, 1920, 1080);
// 创建一个RenderTexture对象 、设置渲染图片的大小和深度
RenderTexture rt = new RenderTexture((int)rect.width, (int)rect.height, 2);
// 临时设置相关相机的targetTexture为rt, 并手动渲染相关相机
camera.targetTexture = rt;
//渲染相机
camera.Render();
// 激活rt, 从中中读取像素。
RenderTexture.active = rt;
Texture2D screenShot = new Texture2D((int)rect.width, (int)rect.height, TextureFormat.RGB24, false);
// 从RenderTexture.active中读取像素
screenShot.ReadPixels(rect, 0, 0, false);
//改变像素设置之后调用的方法()
screenShot.Apply();
//刷新
// 重置相关参数,以使用camera继续在屏幕上显示
camera.targetTexture = null;
//ps: camera2.targetTexture = null;
RenderTexture.active = null;
GameObject.DestroyImmediate(rt);
// 最后将这些纹理数据,成一个png图片文件
byte[] bytes = screenShot.EncodeToPNG();
string filename = Application.dataPath + "/filename.jpg";
Debug.Log(string.Format("截屏了一张照片: {0}", filename));
if (File.Exists(filename)) File.Delete(filename);
System.IO.File.WriteAllBytes(filename, bytes);
}
//生成Texture2D (生成一个黑白相间的图片)
Texture2D texture = new Texture2D(512, 512);
for (int y = 0; y < texture.height; y++)
{
for (int x = 0; x < texture.width; x++)
{
Color color = ((x + y) % 2 == 0 ? Color.white : Color.gray);
//设置位置点像素的颜色
texture.SetPixel(x, y, color);
}
}