- Home /
Help resizing UI at runtime
I have a frame, and then a child of that frame is a photo which is taken at runtime. I need to resize the frame to fit the photo. I've tried the content size fitter but it didn't work or perhaps I'm not using it correctly. Can someone please tell me what components/anchors I need to apply to achieve what I want? Here is an image of it now, and I want the white frame to be snug around the image.
Answer by H3ll0VR · Jan 24, 2019 at 01:18 PM
The aspect ratio fitter component alongside the code below has solved all my problems.
Vector2 imageSize = new Vector2(GetComponent<Image>().sprite.texture.width,
GetComponent<Image>().sprite.texture.height);
float imageRatio = imageSize.x / imageSize.y;
GetComponentInParent<AspectRatioFitter>().aspectRatio = imageRatio;
Answer by xxmariofer · Jan 24, 2019 at 12:32 PM
Click in the anchor button where you can set different predefined anchors, then press alt key and shift key and select the down right corner one
Unfortunately this isn't what I need to do. The photo has a locked aspect. I should have made it clearer in my original post but I believe I need a script which resizes the frame using ratios and the size of the image. Here's what I have currently, with the debugs outputting (-46.6, -70), (-46.6, -70) and (642.0, 964.0) respectively but the image ends up negatively sized:
private void OnEnable()
{
Vector2 frameDelta = GetComponentInParent<RectTransform>().sizeDelta;
Vector2 imageDelta = GetComponent<RectTransform>().sizeDelta;
Vector2 imageSize = new Vector2(GetComponent<Image>().sprite.texture.width,
GetComponent<Image>().sprite.texture.height);
Debug.Log("Frame Delta: " + frameDelta);
Debug.Log("Image Delta: " + imageDelta);
Debug.Log("Image Size: " + imageSize);
float imageRatio = imageSize.x / imageSize.y;
frameDelta.x = frameDelta.y * imageRatio;
imageDelta.x = imageSize.x;
GetComponent<RectTransform>().sizeDelta = imageDelta;
GetComponentInParent<RectTransform>().sizeDelta = frameDelta;
}
Your answer
Follow this Question
Related Questions
Unity UI constant physical size one image 0 Answers
How to use my own image for my UI Slider's Background 2 Answers
UI - Pixel perfect pattern overlay 0 Answers
Image custom fillOrigin 1 Answer
Instanciate prefab responsively 1 Answer