Retina屏图片适配

高清屏解决方案

Retina屏图片适配

如果屏幕的dpr(device pixel ratio)大于1,则屏幕是高清屏,每一个css像素所对应的物理像素不止一个,比如:

  1. dpr:2,一个css像素对应4个物理像素
  2. dpr:3,一个css像素对应9个物理像素

那么如果想针对不同dpr的屏幕提供不同的图片,可以使用如下方案:

Media query(只能用于背景图片)

1
2
3
4
5
6
7
8
.css{/* 普通显示屏(设备像素比例小于等于1.3)使用1倍的图 */ 
background-image: url(img_1x.png);
}
@media only screen and (-webkit-min-device-pixel-ratio:1.5){
.css{/* 高清显示屏(设备像素比例大于等于1.5)使用2倍图 */
background-image: url(img_2x.png);
}
}

Javascript

1
2
3
4
5
6
7
8
9
10
11
$(document).ready(function(){
if (window.devicePixelRatio > 1) {
var lowresImages = $('img');

images.each(function(i) {
var lowres = $(this).attr('src');
var highres = lowres.replace(".", "@2x.");
$(this).attr('src', highres);
});
}
});

Retina屏下0.5px边框问题

因为2倍屏下,1px是由两个物理像素点组成的,所以较1倍屏1px线看起来会粗一点。通常解决办法是在2倍屏下使用0.5px作为边框宽度。比如对于iphone5(dpr=2),添加如下的meta标签,设置viewport(scale 0.5):

1
<meta name="viewport" content="width=640,initial-scale=0.5,maximum-scale=0.5, minimum-scale=0.5,user-scalable=no">

然而,页面scale,必然会带来一些问题:

  1. 字体大小会被缩放
  2. 页面布局会被缩放(如: div的宽高等等

我们也可以使用css3,transform scale来进行元素的缩放,不影响其他元素,或者针对被缩小的元素再进行一次放大,比如

1
2
3
[data-dpr=2] div{
font-size: 32px;
}

rem方案

某些情况下我们希望不同屏幕下的元素大小表现能够适应屏幕,比如一个大标题,在ip6 plus下大一点,ip5下就小一点,我们就可以利用rem的特性来解决。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
var currClientWidth, fontValue, originWidth
//originWidth用来设置设计稿原型的屏幕宽度(这里是以 Iphone 6为原型的设计稿)
originWidth = 375
__resize()

//注册 resize事件
window.addEventListener('resize', __resize, false)

function __resize() {
currClientWidth = document.documentElement.clientWidth
//这里是设置屏幕的最大和最小值时候给一个默认值
if (currClientWidth > 640) currClientWidth = 640
if (currClientWidth < 320) currClientWidth = 320

fontValue = ((16 * currClientWidth) / originWidth).toFixed(2)
document.documentElement.style.fontSize = fontValue + 'px'
}

这样,当我们使用rem作为单位时,不同宽度屏幕下元素的大小表现是不一样的。

原文地址:https://www.cnblogs.com/guochongbin/p/10762695.html