原理:百分比适配(万能适配)。
在AndroidManifest中注明 尺寸 (如:1080x1920)
例: View宽高为 300x200
在 1080x1920 中 View实际 宽高 为 300x200
在 720x1280中 View的实际 宽 为 300*720/1080 = 200 高 为 200*1280/1920 = 133
在 480x800 中 View 宽 300*480/1080 = 133 高为 200*800/1920 = 83
app:layout_auto_basewidth="height",代表height上编写的像素值参考宽度。 //以宽的比值为参考
app:layout_auto_baseheight="width",代表width上编写的像素值参考高度。 //以高的比值为参考
一般设定正方形使用
例如:
View 宽高 300x300 设置app:layout_auto_baseheight="width“
在 480x800手机上
View 宽高都 为300*800/1920= 125
自定义View中有具体数值时:
init()方法中
size=ScreenUtils.getScreenSize(getContext(),true);
widthScreen=size[0];//获取屏幕宽度
heightScreen=size[1];//获取屏幕高度
固定px值转化真实px方法(适配)
/**
* 相对X轴真实PX(宽度)
* @param px
* @return
*/
public int px2width(int px){
return px*widthScreen/AutoLayoutConifg.getInstance().getDesignWidth(); //尺寸宽度 如1080
}
/**
* 相对Y轴真实PX(高度)
* @param px
* @return
*/
public int px2height(int px){
return px*heightScreen/AutoLayoutConifg.getInstance().getDesignHeight();//尺寸高度 如1920
}
不使用参考宽度或高度时:
canvas.drawLine(0,0,px2width(200),px2height(200),mPaint);
//在1080x1920屏幕中 从(0,0) 到 (200,200)之间画一条线
//在720x1920屏幕中 从(0,0)到(133,133)画线
//在480x800屏幕中 从(0,0)到(88,83)画线
参考宽度时:app:layout_auto_basewidth="height"
所有px转化都使用px2width();
参考高度时:app:layout_auto_baseheight="width"
所有px转化都使用px2height();