UI设计师给的设计稿如下:
鸿蒙开发工程师实现页面时,不能直接使用px的数值,大小位置单位应该使用vp,字体大小单位应该使用fp。否则在手机外的其他鸿蒙设备上,页面显示或排版偏差就比较大。 为了解决不同单位转换,我写了一个公共类,代码如下:
import display from '@ohos.display';
import { GlobalContext } from './GlobalContext';
let context = getContext(this);
const DESIGN_WIDTH = 360; // 设计稿宽度
const DESIGN_HEIGHT = 780; // 设计稿高度
/**
* 尺寸适配工具类
*/
export default class SizeUtil {
/**
* 尺寸适配
* @param value 设计稿尺寸
*/
static adaptSize(value: number): number {
let deviceDisplay = GlobalContext.getContext().getObject("globalDisplay") as display.Display;
let widthScale = deviceDisplay.width / DESIGN_WIDTH;
let virtualHeight = DESIGN_HEIGHT * widthScale;
let designDim = Math.sqrt(DESIGN_WIDTH * DESIGN_WIDTH + DESIGN_HEIGHT * DESIGN_HEIGHT);
let virtualDim = Math.sqrt(deviceDisplay.width * deviceDisplay.width + virtualHeight * virtualHeight);
return virtualDim * value / designDim; // 放缩后长度
}
/**
* 获取px
* @param value 设计稿尺寸
*/
static getPx(value: Resource): number {
console.log("context:", context);
let beforeVp = context.resourceManager.getNumber(value.id);
return SizeUtil.adaptSize(beforeVp);
}
/**
* 获取vp
* @param value 设计稿尺寸
*/
static getVp(value: Resource): number {
let beforeVp = context.resourceManager.getNumber(value.id);
return px2vp(SizeUtil.adaptSize(beforeVp));
}
/**
* 获取fp
* @param value 设计稿尺寸
*/
static getFp(value: Resource): number {
let beforeFp = context.resourceManager.getNumber(value.id);
return px2fp(SizeUtil.adaptSize(beforeFp));
}
}
使用时,直接调用函数即可:SizeUtil.getVp($r)