Unity中截图保存成全景图。
public static byte[] Render2Panorama(Camera cam = null,bool save =false)
{
//可修改数值 new RenderTexture(4096, 4096, 32);
RenderTexture cubemap = new RenderTexture(2048, 2048, 16);
cubemap.dimension = TextureDimension.Cube;
cam.RenderToCubemap(cubemap, 63, Camera.MonoOrStereoscopicEye.Mono);
//可修改数值 new RenderTexture(4096, 4096, 32);
RenderTexture equirect = new RenderTexture(1920, 1080, 8);
cubemap.ConvertToEquirect(equirect, Camera.MonoOrStereoscopicEye.Mono);
RenderTexture.active = equirect;
Texture2D tex = new Texture2D(equirect.width, equirect.height, TextureFormat.ARGB32, false, true);
tex.ReadPixels(new Rect(0, 0, tex.width, tex.height), 0, 0);
RenderTexture.active = null;
GL.Clear(true, true, Color.black);
tex.Apply();
byte[] bytes = tex.EncodeToJPG();
// CreateDirectroryOfFile(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Desktop) + "\\全景图\\)");
// System.IO.File.WriteAllBytes(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Desktop)
// + "\\全景图\\" + System.DateTime.Now.Ticks + ".tga", bytes);
if (save)
{
string path = Path.Combine(Application.dataPath,"../","Panorama");
if (!System.IO.Directory.Exists(path)) Directory.CreateDirectory(path);
File.WriteAllBytes(path+ "/" + Time.time.ToString()+ ".jpg", bytes);
}
return bytes;
}
假定图片为2048*1024,坐标起始点为左下角。
public class uv计算坐标 : MonoBehaviour
{
// Start is called before the first frame update
public Vector2 uv;
private Vector3[] _vertArr;
private Vector2[] _uvArr;
void Start()
{
uv = uv / new Vector2(2048, 1024);
var mesh = GetComponent<MeshFilter>().mesh;
_vertArr = mesh.vertices;
_uvArr = mesh.uv;
var index =FindClosestVector(uv);
var pos = Uv2Pos(index);
CreatePoint(pos);
}
public GameObject CreatePoint(Vector3 pos)
{
var go = GameObject.CreatePrimitive(PrimitiveType.Sphere);
go.transform.localScale = Vector3.one/10;
go.transform.position = pos;
go.name = pos.ToString();
return go;
}
public Vector3 Uv2Pos( int index)
{
var vr = _vertArr;
return transform.TransformPoint(_vertArr[index]);
}
// Update is called once per frame
public int FindClosestVector( Vector2 target)
{
Vector2[] vectors = _uvArr;
// Vector2 closestVector = vectors[0];
int index = 0;
float closestDistance = Vector2.Distance(vectors[0], target);
for (int i = 1; i < vectors.Length; i++)
{
float distance = Vector2.Distance(vectors[i], target);
if (distance < closestDistance)
{
// closestVector = vectors[i];
closestDistance = distance;
index = i;
}
}
return index;
}
}