2D Toolkit Forum
2D Toolkit => Support => Topic started by: aCallum on March 19, 2013, 07:59:57 pm
-
Hey guys, I'm wondering if it's possible to extract the data of a tk2dsprite into a texture2D or byte[] object?
I'm wanting to send the image data over the internet. For example, we have an atlas texture containing medals (gold/silver/bronze) that are diplayed in game, when you complete a mission you can share your success via Facebook; including the medal image.
I know I can get the material and then the texture, but how can I get the texture data only for the current tk2dsprite area of that texture?
Cheers!
-
You'd have to derive it out from
sprite.CurrentSprite.uvs
But be aware, most textures aren't set up to be readable.
It might be easier and more efficient to render a sprite into a rendertarget, and then capture the contents of the render target instead.
-
Interesting, can you explain to me which elements of the UVs Vector2[] object equal what?
How I can calculate the width/height and x/y pixel units? I'd imagine something like (TextureWidth / 100.0f) * UVs.x ?
-
Well, a couple of hours and I have a solution that works for my needs. The only problem is it will not handle sprites that have been rotated on the atlas because I get the UV's explicitly.
public static Texture2D SpriteToTexture(tk2dSprite sourceSprite) {
Texture2D sourceTexture = (Texture2D)sourceSprite.GetCurrentSpriteDef().material.mainTexture;
Vector2[] UVs = sourceSprite.GetCurrentSpriteDef().uvs;
// Get the raw uv-pixel co-ordinates of the image.
float fX = (sourceTexture.width) * UVs[0].x;
float fY = (sourceTexture.height) * UVs[2].y;
float fX2 = (sourceTexture.width) * UVs[1].x;;
float fY2 = (sourceTexture.height) * UVs[0].y;
// Calculate the width and height of the sprite.
float fWidth = fX2 - fX;
float fHeight = -(fY2 - fY);
// Round the values to pixel units.
int x = Mathf.RoundToInt(fX);
int y = Mathf.RoundToInt(fY - fHeight);
int width = Mathf.RoundToInt(fWidth);
int height = Mathf.RoundToInt(fHeight);
// Get the pixels contained within the pixel units of the atlas.
Color[] pixelRect = sourceTexture.GetPixels(x, y, width, height);
// Generate a new texture and populate it with the pixel data.
Texture2D newTexture = new Texture2D(width, height);
newTexture.SetPixels(pixelRect);
newTexture.Apply();
return newTexture;
}
I'll leave this here for anyone else that may be interested.
-
Thanks for sharing :)