JS实现图片大小自适应且位置居中,防止图片变形

/*
2016-7-29
图片大小自适应,防止图片变形
其中 maxWidth 是图片显示的最大宽度,maxHeight 是图片显示的最大高度,

1.均为0则不进行缩放,
2.maxWidth=0,且实际高度>maxHeight时,以高度缩放比例缩小,
3.maxHeight=0,且实际宽度>maxWidth时,以宽度缩放比例缩小,
4.实际高度>maxHeight,且实际宽度>maxWidth时,则以缩放比例小的进行缩小,
5.否则不对图片进行缩放。

调用示例
*/
function AutoResizeImage(maxWidth, maxHeight, objImg) {
var img = new Image();
img.src = objImg.src;
var hRatio;
var wRatio;
var Ratio = 1;
var w = img.width; //图片实际宽度
var h = img.height;
wRatio = maxWidth / w; //宽度缩放比
hRatio = maxHeight / h;
if (maxWidth == 0 && maxHeight == 0) {
Ratio = 1;
}
else if (maxWidth == 0) {
if (hRatio < 1) Ratio = hRatio;
}
else if (maxHeight == 0) {
if (wRatio < 1) Ratio = wRatio;
}
else if (wRatio < 1 || hRatio < 1) {
Ratio = (wRatio <= hRatio ? wRatio : hRatio);
if (wRatio < hRatio) {
objImg.style.marginTop = (maxHeight - h * Ratio) / 2 + ‘px’; //使图片垂直居中
}
else {
objImg.style.marginLeft = (maxWidth - w * Ratio) / 2 + ‘px’; //使图片水平居中
}
}
else {
objImg.style.marginTop = (maxHeight - h) / 2 + ‘px’;
objImg.style.marginLeft = (maxWidth - w) / 2 + ‘px’;
}
if (Ratio < 1) {
w = w * Ratio; h = h * Ratio;
}
objImg.height = h; objImg.width = w;
}

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在Unity中,可以通过调用RectTransform组件的AdaptiveUI方法来实现图片的大小自适应。首先,你需要一个UI父物体或者单独的UI元素,然后在Awake方法中调用相应的方法即可实现自适应。比如,你可以在脚本中创建一个UITest类,在Awake方法中调用UIImage的AdaptiveUIImage方法来实现图片大小自适应。以下是一个示例代码: ```csharp public class UITest : MonoBehaviour { public RectTransform UIParent; public Image UIImage; void Awake() { UIParent.AdaptiveUI(); UIImage.AdaptiveUIImage(); } } ``` 在Awake方法中,可以根据屏幕的比例来计算需要缩放的比例,然后通过transform.localScale来进行缩放。以下是一个示例代码: ```csharp private void Awake() { float p1 = (float)Screen.width / 1028f; float p2 = (float)Screen.height / 600f; float p = p1 < p2 ? p1 : p2; transform.localScale = Vector3.one * p; } ``` 这样,图片就会根据屏幕的比例进行自适应调整大小。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* [Unity UI自适应 Image自适应 Text自适应](https://blog.csdn.net/CTangZe/article/details/118211091)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] - *3* [Unity 实现UI自适应](https://blog.csdn.net/slf_tragon/article/details/130935444)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值