Adjust RectTransform width to image that is scaled down
What I would like to know if the following is possible and how?
Create UI Canvas, with one GameObject and a Horizontal Layout Group on it
Add 2 GameObjects to it, one with any Text, one with an image
Enable keep aspect on that image
shrink the vertical size of the layout group down
The image will keep it's aspect, but it's containing RectTransform is as wide as the image would be if stretched. How do you get the RectTransform to uniformly adjust to the visual size of the image?
Answer by Addyarb · Oct 27, 2015 at 01:05 AM
It's sort of hard to understand what you're trying to do, but attach this script to your GameObject with the HZLayout on it.
Then:
Enter Playmode and change regular to debug (dropdown/enum)
Adjust parameters to get object where you want it
Memorize/Copy parameters
Exit Playmode
Change/Paste parameters
Make sure to turn debug mode back to regular
using UnityEngine; using System.Collections;
public class SizeBasedOnScreenWidth : MonoBehaviour
{
public enum modes { regular, debug }
public modes mode;
public Vector2 screenPosition;
Vector2 lastScreenSize;
RectTransform rt;
public float customScaleRatio = .001f;
// Use this for initialization
void Start()
{
if (customScaleRatio == 0) customScaleRatio = .001f;
rt = GetComponent<RectTransform>();
SetScreenSize();
}
void Update()
{
if (Screen.width != lastScreenSize.x || Screen.height != lastScreenSize.y || mode == modes.debug)
SetScreenSize();
}
void SetScreenSize()
{
rt.anchoredPosition = new Vector2(Screen.width * screenPosition.x, Screen.height / screenPosition.y);
rt.localScale = new Vector2(Screen.width * customScaleRatio, Screen.height * customScaleRatio);
rt.localScale = new Vector2(rt.localScale.x, rt.localScale.x);
lastScreenSize = new Vector2(Screen.width, Screen.height);
}
}
Thanks for that answer, but I'm looking for a solution that works with auto layout elements only. I don't want to adjust the content on a value basis.
Here's an image of what I meant in my question:
First image is more as expected, the image doesn't get any bigger as its actual size. But in the second image, the image is smaller but keeps its full width, the RectTransform does not adjust to the size, which means its not oriented on the right.
Your answer
Follow this Question
Related Questions
RectTransform Left Right Bottom Top 0 Answers
Drag and drop pivot point, Rect Transform 1 Answer
Aspect ratio boxes floor 0 Answers
UI RectTransform.rect.width/heigth returns incorrect/negative values 0 Answers