Resize a sprite on a sprite renderer
I've got a Sprite inside a Sprite Renderer and it looks great. However, when I click a button I want that sprite to change from one Sprite to another. However, my second sprite is much larger than the first. As a result, it's overflowing my Sprite Renderer.
Here is the code attached to my button:
public Sprite[] myCardSprites;
public void changeCardArtwork ()
{
GameObject g = GameObject.FindGameObjectWithTag ("CardArt");
SpriteRenderer s = g.GetComponent<SpriteRenderer> ();
foreach (Sprite currentSprite in myCardSprites)
{
//Set the image to the Rhino
if (currentSprite.name == "Rhino")
{
s.sprite = currentSprite;
}
}
}
I've tried a couple of differnt things like changing the transform.localscale on the SpriteRender and tried Sprite.texture.Resize. I also tried to add a Rect Transform onto my SpriteRender to sort of set bounds. Nothing has worked so far.
What I'd love to happen is for the sprite to just take on the size of the sprite renderer.
Thanks in advance.
For a workaround, I've resized all of my sprites to be the same size. The two answers below sort of have me thinking it's based on the size of the screen, and that I'd have to do some calculations to fit a randomly sized image into my sprite renderer.
http://answers.unity3d.com/questions/620699/scaling-my-background-sprite-to-fill-screen-2d-1.html
http://answers.unity3d.com/questions/1042119/getting-a-sprites-size-in-pixels.html
Something like
Figure out the size in PX of the sprite
Figure out the size of the screen
Figure out the size of the sprite renderer
Scale the sprite renderer by some factor X to match the amount of space I want it to take up on the screen.
In the end it was less brain work to just resize each sprite. I'll leave the question here unanswered unless someone wants me to close it, in case someone wants to comment for a future person to use.
Answer by LZakhar · Aug 14, 2017 at 08:53 PM
@dhaggerfin if this would help you I`ve used next script to scale sprites to one size. Note that they must be read\write enabled.
private Texture2D ScaleTexture(Texture2D source, int targetWidth, int targetHeight)
{
Texture2D result = new Texture2D(targetWidth, targetHeight, source.format, true);
Color[] rpixels = result.GetPixels(0);
float incX = (1.0f / (float)targetWidth);
float incY = (1.0f / (float)targetHeight);
for (int px = 0; px < rpixels.Length; px++)
{
rpixels[px] = source.GetPixelBilinear(incX * ((float)px % targetWidth), incY * ((float)Mathf.Floor(px / targetWidth)));
}
result.SetPixels(rpixels, 0);
result.Apply();
return result;
}