FM/Assets/Scripts/FUJIFILM/UI/ImageScaler.cs

66 lines
2.4 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

using UnityEngine;
using UnityEngine.UI;
namespace HK.FUJIFILM
{
public static class ImageScaler
{
/// <summary>
/// 将Image等比缩放到不超过指定的最大尺寸宽和高中较大的值不超过maxSize
/// </summary>
/// <param name="image">需要缩放的Image组件</param>
/// <param name="maxSize">宽和高中较大值的最大限制</param>
/// <param name="keepOriginalIfSmaller">如果原图比限制小,是否保持原图大小</param>
public static void ScaleImageWithMaxSize(Image image, float maxSize, bool keepOriginalIfSmaller = false)
{
if (image == null)
{
Debug.LogError("Image组件不能为空");
return;
}
// 获取原始尺寸
float originalWidth, originalHeight;
if (image.sprite != null)
{
// 使用Sprite的原始尺寸
originalWidth = image.sprite.rect.width;
originalHeight = image.sprite.rect.height;
}
else
{
// 没有Sprite时使用当前RectTransform的尺寸
originalWidth = image.rectTransform.rect.width;
originalHeight = image.rectTransform.rect.height;
}
// 计算缩放比例
float scaleRatio = CalculateScaleRatio(originalWidth, originalHeight, maxSize, keepOriginalIfSmaller);
// 应用缩放后的尺寸
image.rectTransform.sizeDelta = new Vector2(
originalWidth * scaleRatio,
originalHeight * scaleRatio
);
}
/// <summary>
/// 计算缩放比例
/// </summary>
private static float CalculateScaleRatio(float originalWidth, float originalHeight, float maxSize, bool keepOriginalIfSmaller)
{
// 找到原始宽高中的较大值
float maxOriginal = Mathf.Max(originalWidth, originalHeight);
// 如果原图的最大边小于等于限制值,且需要保持原图大小,则不缩放
if (maxOriginal <= maxSize && keepOriginalIfSmaller)
{
return 1f; // 不缩放
}
// 计算缩放比例让最大边刚好等于maxSize
return maxSize / maxOriginal;
}
}
}