Unity 3D通过Image的固定高度计算图片(Sprite)放大或缩小后的宽度
原图片分辨率是480*320 计算之前
计算之后 代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Test : MonoBehaviour
{
[Header("Image(UI组件)")]
public Image image;
[Header("资源图片")]
public Sprite sprite;
void Start()
{
Width();
}
void Width()
{
float h = image.GetComponent<RectTransform>().sizeDelta.y / sprite.bounds.size.y;
float w = sprite.bounds.size.x * h;
image.GetComponent<RectTransform>().sizeDelta = new Vector2(w, image.GetComponent<RectTransform>().sizeDelta.y);
image.sprite = sprite;
}
void Height()
{
float w = image.GetComponent<RectTransform>().sizeDelta.x / sprite.bounds.size.x;
float h = sprite.bounds.size.y * w;
image.GetComponent<RectTransform>().sizeDelta = new Vector2(image.GetComponent<RectTransform>().sizeDelta.x, h);
image.sprite = sprite;
}
}
脚本挂在哪都一样变量赋值对了就行 image.GetComponent().sizeDelta.y 是Image的Heighe image.GetComponent().sizeDelta.x 是Image的Width
|