小程序 获取图片自适应屏幕的尺寸大小

图片按比例填充容器,不需要获取详细的图片大小。

可以直接设置图片裁剪、缩放的模式mode=aspectFit

而某些场景,比如画布上绘制图片,需要获取保持纵横比自适应的图片大小~

直接上代码,方便大家copy~

 1     getImageScaleSize = async (imagePath) => {
 2         var imageSizeInfo = { width: 0, height: 0 };
 3 
 4         //原始宽高
 5         var imageInfo = await Taro.getImageInfo({
 6             src: imagePath
 7         });
 8         var originalWidth = imageInfo.width;
 9         var originalHeight = imageInfo.height;
10         var originalScale = originalHeight / originalWidth;
11         console.log('originalWidth: ' + originalWidth + ',originalHeight: ' + originalHeight + ',originalScale: ' + originalScale);
12 
13         //屏幕宽高
14         var systemInfo = Taro.getSystemInfoSync();
15         var windowWidth = systemInfo.windowWidth;
16         var windowHeight = systemInfo.windowHeight;
17         var windowscale = windowHeight / windowWidth;
18         console.log('windowWidth: ' + windowWidth + ',windowHeight: ' + windowHeight + ',windowscale: ' + windowscale);
19 
20         if (originalScale < windowscale) {
21             //图片高宽比小于屏幕高宽比
22             //图片缩放后的宽为屏幕宽
23             imageSizeInfo.width = windowWidth;
24             imageSizeInfo.height = (windowWidth * originalHeight) / originalWidth;
25         } else {
26             //图片高宽比大于屏幕高宽比
27             //图片缩放后的高为屏幕高
28             imageSizeInfo.height = windowHeight;
29             imageSizeInfo.width = (windowHeight * originalWidth) / originalHeight;
30         }
31         console.log('缩放后的宽: ' + imageSizeInfo.width + '缩放后的高: ' + imageSizeInfo.height + ',windowscale: ' + windowscale);
32         return imageSizeInfo;
33     }

注:如果是用原生微信框架,将Taro换成wx就行。

如是容器内添加图片,可以通过wx.createSelectorQuery()获取容器的宽高,再对图片添加缩放处理。

1     const query = wx.createSelectorQuery()
2     query.select('.body').boundingClientRect()
3     query.selectViewport().scrollOffset()
4     query.exec(async (res) => {
5         var containerWidth = res[0].width;
6         var containerHeight = res[0].height;
7     })

缩放效果:

 

 

posted @ 2020-09-11 10:31  唐宋元明清2188  阅读(714)  评论(0编辑  收藏  举报