简单分析 Android4.0.4里 Launcher2 中的 workspace.java文件中的函数 wallpaperTravelToScreenWidthRatio
// As a ratio of screen height, the total distance we want the parallax effect to span
// horizontally
private float wallpaperTravelToScreenWidthRatio(int width, int height) {
float aspectRatio = width / (float) height;
// At an aspect ratio of 16/10, the wallpaper parallax effect should span 1.5 * screen width
// At an aspect ratio of 10/16, the wallpaper parallax effect should span 1.2 * screen width
// We will use these two data points to extrapolate how much the wallpaper parallax effect
// to span (ie travel) at any aspect ratio:
final float ASPECT_RATIO_LANDSCAPE = 16/10f;
final float ASPECT_RATIO_PORTRAIT = 10/16f;
final float WALLPAPER_WIDTH_TO_SCREEN_RATIO_LANDSCAPE = 1.5f;
final float WALLPAPER_WIDTH_TO_SCREEN_RATIO_PORTRAIT = 1.2f;
// To find out the desired width at different aspect ratios, we use the following two
// formulas, where the coefficient on x is the aspect ratio (width/height):
// (16/10)x + y = 1.5
// (10/16)x + y = 1.2
// We solve for x and y and end up with a final formula:
final float x =
(WALLPAPER_WIDTH_TO_SCREEN_RATIO_LANDSCAPE - WALLPAPER_WIDTH_TO_SCREEN_RATIO_PORTRAIT) /
(ASPECT_RATIO_LANDSCAPE - ASPECT_RATIO_PORTRAIT);
final float y = WALLPAPER_WIDTH_TO_SCREEN_RATIO_PORTRAIT - x * ASPECT_RATIO_PORTRAIT;
return x * aspectRatio + y;
}
这个函数最终的返回结果是一个 float 型,通过名字很容易猜到是一个比率值 (Ratio),是可滑动区域的宽度与屏幕宽度的比率。
这个函数的作用是想通过屏幕的宽和高,计算出可滑动区域的宽度与屏幕宽度的比值。
因为LANDSCAPE和PORTRAIT模式,即横屏平板和竖屏手机模式在计算逻辑上没有区别,屏幕横纵比与滑动宽度固定宽度比成线性关系,根据这个关系,建立了关系
屏幕横纵比 * x + y = 滑动宽度固定宽度比
谷歌定义了两种情况:
第一种是平板LANDSCAPE模式情况下,选择的参考模型是屏幕分辨率的横纵比为16/10的设备,滑动宽度固定宽度比为1.5,即在平板设备上,我们可滑动屏幕区域是屏幕宽度的1.5倍;
第二种是手机PORTRAIT模式情况下,选择的参考模型是屏幕分辨率的横纵比为10/16的设备,滑动宽度固定宽度比为1.2,即在手机设备上,我们可滑动屏幕区域是屏幕宽度的1.2倍;
根据这两种情况定义的线性关系,建立了多项式:
(16/10)x + y = 1.5
(10/16)x + y = 1.2
对上述的多项式,求解,就得出了x和y的值:
final float x =
(WALLPAPER_WIDTH_TO_SCREEN_RATIO_LANDSCAPE - WALLPAPER_WIDTH_TO_SCREEN_RATIO_PORTRAIT) /
(ASPECT_RATIO_LANDSCAPE - ASPECT_RATIO_PORTRAIT);
final float y = WALLPAPER_WIDTH_TO_SCREEN_RATIO_PORTRAIT - x * ASPECT_RATIO_PORTRAIT;
根据我们函数传入参数,得到了屏幕横纵比
float aspectRatio = width / (float) height;
把此值代入关系式
屏幕横纵比 * x + y = 滑动宽度固定宽度比
就可以得到
滑动宽度固定宽度比 了,也就是我们函数最终要返回的值。