前端uni-app移动端开发怎么适配@1x、@2x、@3x图片,直接使用 IMG 的 SRCSET 属性无效
时间: 2024-01-05 17:05:20 浏览: 178
在前端uni-app移动端开发中,可以使用 CSS 的媒体查询和像素比(device pixel ratio)来适配 @1x、@2x、@3x 图片。
具体做法是:
1. 在 CSS 中使用媒体查询,根据不同的屏幕宽度设置不同的图片大小,例如:
```css
/* iPhone 6/7/8 */
@media screen and (max-width: 375px) {
.my-image {
width: 100px;
height: 100px;
}
}
/* iPhone 6/7/8 Plus */
@media screen and (min-width: 376px) and (max-width: 414px) {
.my-image {
width: 120px;
height: 120px;
}
}
/* iPad */
@media screen and (min-width: 415px) {
.my-image {
width: 160px;
height: 160px;
}
}
```
2. 在 HTML 的 IMG 标签中使用像素比(device pixel ratio),例如:
```html
<template>
<img :src="getImageSrc()" :srcset="getImageSrcset()">
</template>
<script>
export default {
methods: {
getImageSrc() {
let pixelRatio = uni.getSystemInfoSync().pixelRatio;
if (pixelRatio === 1) {
return "image@1x.png";
} else if (pixelRatio === 2) {
return "image@2x.png";
} else if (pixelRatio === 3) {
return "image@3x.png";
} else {
return "image@1x.png";
}
},
getImageSrcset() {
return "image@2x.png 2x, image@3x.png 3x";
},
},
};
</script>
```
这样,如果设备的像素比是 1,则会加载 image@1x.png;如果像素比是 2,则会加载 image@2x.png;如果像素比是 3,则会加载 image@3x.png。
需要注意的是,在使用像素比时,必须保证图片的实际大小与 CSS 设置的大小一致,否则会出现变形或者模糊等问题。
阅读全文
相关推荐


















