- Home /
Question by
ina · May 29, 2019 at 12:05 PM ·
rendertexturespriterendererscreenshot
Screenshot from a rendertexture (non-main camera) to fit sprite (in 3D space) exactly
How do you adjust or otherwise set up a screenshot to have the exact dimensions of a particular sprite that is in 3D space (so, Gameobject with SpriteRenderer).
The render camera is set up directly above the sprite but has some black space outside.
Comment
Answer by xxmariofer · May 29, 2019 at 12:57 PM
cant test this but should work
void CreateSprite () {
int pixels = 100;//change the amount of pixels per unit here
var texture = new Texture2D(pixels, pixels, TextureFormat.ARGB32, false);
string path = Application.dataPath + "/Image.png";
ScreenCapture.CaptureScreenshot(path);
byte[] data = null;
if(File.Exists(path))
{
data = File.ReadAllBytes(path);
}
else
{
Debug.Log("Screen wasnt captured?");
return;
}
texture.LoadImage(data);
Color[] pix = texture.GetPixels();
for (int i = 0; i < pix.Length; i++)
pix[i].a = pix[i].grayscale;
texture.SetPixels(pix);
texture.Apply();
GetComponent<SpriteRenderer>().sprite = Sprite.Create(texture, new Rect(0.0f, 0.0f, texture.width, texture.height), new Vector2(0.5f, 0.5f), pixels);
}