Home > Enterprise >  Unity - How to change sprite size to fixed resoltion in code
Unity - How to change sprite size to fixed resoltion in code

Time:07-22

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?

CodePudding user response:

Not sure how exactly you want to resize an image (make it smaller, or cut the part of it), but you can play around with Sprite.Create method

CodePudding user response:

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.

  • Related