Cute_demon_attacks/meng_yao/Assets/communal/ugui/adaptive_ui.cs
2024-10-18 23:06:26 +08:00

39 lines
1.1 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class adaptive_ui : MonoBehaviour
{
public RawImage rawImage; // 使用RawImage组件展示纹理
public RectTransform boundaryRect; // 代表边界矩形的RectTransform
void Start()
{
ScaleAndCropTexture();
}
void ScaleAndCropTexture()
{
Texture texture = rawImage.texture;
float textureWidth = texture.width;
float textureHeight = texture.height;
float boundaryWidth = boundaryRect.rect.width;
float boundaryHeight = boundaryRect.rect.height;
// 计算缩放比例,确保较短的一边适应边界矩形
float scaleFactor = Mathf.Max(boundaryWidth / textureWidth, boundaryHeight / textureHeight);
// 设置缩放后的尺寸
float newWidth = textureWidth * scaleFactor;
float newHeight = textureHeight * scaleFactor;
// 设置RawImage的RectTransform尺寸使其居中并覆盖边界矩形
rawImage.rectTransform.sizeDelta = new Vector2(newWidth, newHeight);
// 裁剪超出的部分
rawImage.rectTransform.anchoredPosition = Vector2.zero; // 确保居中
}
}