【微信小程序】根据屏幕尺寸去调整图片尺寸宽高比
程序员文章站
2022-03-21 23:37:27
1.获取图片的原始宽高,并获取到图片原始宽高的宽高比let src = "图片地址"wx.getImageInfo({ src, success: function(res){ let originalWidth = res.width; let originalHeight = res.height; let originalScale = parseInt(originalHeight/originalWidth);//图片高宽比...
1.获取图片的原始宽高,并获取到图片原始宽高的宽高比
let src = "图片地址"
wx.getImageInfo({
src,
success: function(res){
let originalWidth = res.width;
let originalHeight = res.height;
let originalScale = parseInt(originalHeight/originalWidth);//图片高宽比
}
})
2.获取屏幕的宽高,并获取到屏幕宽高的宽高比
wx.getSystemInfo({
success: function (res) {
let windowWidth = res.windowWidth - 36 ;
let windowHeight = res.windowHeight;
let windowscale = parseInt(windowHeight/windowWidth);//屏幕高宽比
}
})
3.计算图片尺寸
if(originalScale < windowscale){//图片高宽比小于屏幕高宽比
//图片缩放后的宽为屏幕宽
imageSize.imageWidth = parseInt(windowWidth);
imageSize.imageHeight = parseInt((windowWidth * originalHeight) / originalWidth);
}else{//图片高宽比大于屏幕高宽比
//图片缩放后的高为屏幕高
imageSize.imageHeight = parseInt(windowHeight);
imageSize.imageWidth = parseInt((windowHeight * originalWidth) / originalHeight);
}
4.整合代码,方便调用 新建一个util.js
function imageUtil(src,callback) {
let imageSize = {};
wx.getImageInfo({
src,
success: function(res){
console.log(res,"1111111111111111111111")
let originalWidth = res.width;
let originalHeight = res.height;
let originalScale = parseInt(originalHeight/originalWidth);//图片高宽比
console.log('originalWidth: ' + originalWidth)
console.log('originalHeight: ' + originalHeight)
console.log(app.globalData)
wx.getSystemInfo({
success: function (res) {
let windowWidth = res.windowWidth - 36 ;
let windowHeight = res.windowHeight;
let windowscale = parseInt(windowHeight/windowWidth);//屏幕高宽比
console.log('windowWidth: ' + windowWidth)
console.log('windowHeight: ' + windowHeight)
if(originalScale < windowscale){//图片高宽比小于屏幕高宽比
//图片缩放后的宽为屏幕宽
imageSize.imageWidth = parseInt(windowWidth);
imageSize.imageHeight = parseInt((windowWidth * originalHeight) / originalWidth);
}else{//图片高宽比大于屏幕高宽比
//图片缩放后的高为屏幕高
imageSize.imageHeight = parseInt(windowHeight);
imageSize.imageWidth = parseInt((windowHeight * originalWidth) / originalHeight);
}
},
})
console.log('缩放后的宽: ' + imageSize.imageWidth)
console.log('缩放后的高: ' + imageSize.imageHeight)
return callback(imageSize);
}
})
//抛出
module.exports = {
imageUtil,
}
本文地址:https://blog.csdn.net/qq_37949737/article/details/109247673
上一篇: 网站软文创写方法有哪些?
下一篇: 软文推广为何没有预期的好