- Home /
Convert a Texture2D to Sprite
Hello,
I would like to convert an array of Texture2D to an array or Sprites.
I tried this method:
Sprite.Create(texture, rect, pivot);
But how to set the exact rect and the exact pivot of a texture?
thanks.
Answer by TrevorP · Feb 26, 2014 at 04:34 PM
The rectangle parameter is the source rectangle on the texture. If you want to use the whole texture as the sprite, use new Rect(0, 0, texture.width, texture.height);
I believe the pivot is actually a percentage and not a pixel/unit value. So if you wanted to pivot at the center of the texture you would use new Vector2(0.5f, 0.5f)
Sorry for the pseudo code, away from Unity at the moment.
Hope this helps!
I use Rect rec = new Rect(0, 0, texture.width, texture.height);
dust.GetComponent ().sprite=Sprite.Create(texture,rec,new Vector2(0.5f,0.5f),100);
But result is image became small than before sprite.
Someone know how to solve.
Thanks for the help!
@hauzz You need to change "pixelsPerUnit" in Sprite.Create() , i.e. change "100" in your code. The pixelsPerUnit value controls the size of the sprite. Reducing this below 100 pixels per world increases the size of the sprite.
Also, The issue could have been that the texture that you would have imported would be of greater pixel size(lets says 2048*2048) and while importing in unity, you would have reduced the maximum size(e.g. 1024). This made the sprite created from the texture to be smaller than actual when you loaded it using Sprite.Create().
^ Saved me loads of time, could not figure out why so tiny. Thanks =)
Answer by Bilelmnasser · Apr 04, 2017 at 07:00 AM
hello, maybe it's a late reply but my suggestion is : when you dealing with sprite downloaded and created at Runtime , i recommand to use RawImage better than UIimage because Sprite.Create use more CPU example :
using UnityEngine;
using System.Collections;
// Get the latest webcam shot from outside "Friday's" in Times Square
public class ExampleClass : MonoBehaviour
{
public RawImgae Rimage;
public string url = "https://worldcams.tv/images/small/89.jpg";
IEnumerator Start()
{
// Start a download of the given URL
WWW www = new WWW(url);
// Wait for download to complete
yield return www;
// assign texture
Rimage.texture = www.texture;
}
}
Your answer
Follow this Question
Related Questions
Loading a Sprite (Unity 4.3) in resource folder and setting it in sprite renderer 6 Answers
Converting transparent Texture2D to Sprite 0 Answers
Load Unity 4.3 Sprites with AssetBundles 5 Answers
why texture2d sprite rendering not showing in game 0 Answers
How to read sprites/textures from an Animator current animation? 0 Answers