Search code examples
c#unity-game-enginebitmapspriteresolution

Unity - How to change sprite size to fixed resoltion in code


I have a set of sprites with different resolutions and aspect ratios. I want to create new sprites based on the original sprites but with a fixed 20 x 20 resolution.

When working with bitmaps, what I did was this: Bitmap newImage = new Bitmap(oldImage, new Size(20, 20));

But Unity's Sprites don't have any constructors. How can I do this?


Solution

  • There are 2 ways to create Sprites from image or original sprite. from image code below..

    string url = "";//image url;
    WWW image = new WWW(url);
    yield return image;
    Texture2D texture = new Texture2D(1, 1);
    image.LoadImageIntoTexture(texture);
    Sprite newSprite = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), new Vector2(0, 0), 1);
    RectTransform rt = newSprite.GetComponent<RectTransform>();
    rt.sizeDelta = new Vector2(20, 20);//make 20px * 20px sprite
    

    clone sprite code below..

    Sprite cloneSprite = Instantiate(originalSprite);
    RectTransform rt = cloneSprite.GetComponent<RectTransform>();
    rt.sizeDelta = new Vector2(20, 20);//make 20px * 20px sprite
    

    I hope it will work on your project.