Scaling an image sent to UI Image
Disclaimer: I have already looked at similar questions , and the wiki entry for TextureScale.cs ; and found no solutions that worked so far.
Objective
- 64 wide by 128 tall container holding a
- middle center 64x64 image, or 32x32 image, or 128x128 image...
Logical steps required
- Load copy or clone original Texture (varying sizes)
- Determine the ratio for scaling the X and Y of image
- use Texture2D.Resize or similar, or draw scaled image
Current Code
void DrawItem(string imagecanvas, Texture2D texture) {
// Make a copy of the item's icon.
Texture2D temp = Instantiate(texture) as Texture2D;
// Find largest axis and clamp both.
float ratioW = 256 / (float)temp.width;
float ratioH = 256 / (float)temp.height;
float ratio;
ratio = (ratioH<ratioW?ratioH:ratioW);
// Apply calculated ratios
temp.Resize( (int)(temp.width*ratio), (int)(temp.height*ratio) );
// place Sprite back in Canvas
Vector2 p = new Vector2(0.5f, 0.5f);
Sprite sprite = Sprite.Create(temp, new Rect(0, 0, temp.width, temp.height), p);
GameObject.Find(imagecanvas).GetComponent<Image>().sprite = sprite;
}
Current Behaviour
- Depending on the size of the texture handed to it, the area either has no texture drawn (entirely transparent) ; or it's nowhere near centered / in the Rect bounds as given by the parent Image.
EDIT : Updated the code and issue above.
EDIT : I've also tried creating runtime Materials with the mainTexture set via SetTexture(0, texture); mainTexture = texture; still no go. It simply doesn't change, the original sprite / texture is all that's shown now.
Now it's refusing to update at all when changed at Runtime!
Canvas is garbage! I'm going back to OnGUI and DrawRect :(.
Edit If you use only RawImage in the Canvas, it finally listens to the changes to the Texture property (via .texture = texture) ; but I cannot resize this texture, the exact same thing happens (it expects the texture I give it be larger than the area I want to draw on, which can't be done if I'm resizing it down...)