- Home /
How to create Sprite programmatically
Hi, I need to programmatically create a Texture2D from an image file and to then create a Sprite from it. I then need to assign this sprite to the Image component.
The following code does exactly that but the problem is that the Image only shows the bottom left 25% of the original texture and not all of it. For example if I create the sprite in the editor and then assign to the Image component, it displays properly showing the whole texture. this is not the case if I do it programmatically using the following code:
byte[] fileData = File.ReadAllBytes(userImagePath);
Texture2D texture2D = new Texture2D(2, 2);
texture2D.LoadImage(fileData); //..this will auto-resize the texture dimensions.
Sprite sp = Sprite.Create(texture2D,new Rect(0,0,texture2D.width,texture2D.height),new Vector2(1.0f,1.0f));
Image.sprite =sp;
Answer by Nims · Jul 23, 2015 at 10:54 AM
Last parameter of Sprite.Create is the pivot, set it to: new Vector2(0.5f,0.5f)
Your answer
Follow this Question
Related Questions
Unity 5.0 Trying to Change the Image - Source Image via Script 3 Answers
Changing Sprites Color According to Value 2 Answers
Messy tiled sprites 1 Answer
Stop Texture2D Compression 0 Answers
Get current sprite from filled Image PRESERVING ITS TRANSPARENCY 0 Answers