ScreenAdapter.ts 3.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. /**
  2. * 该类用于屏幕适配,一般挂载与Canvas节点
  3. */
  4. import { _decorator, Component, Node, UITransform, View, Widget ,screen} from 'cc';
  5. const { ccclass, property } = _decorator;
  6. @ccclass('Adapter')
  7. export class ScreenAdapter extends Component {
  8. public static instance: ScreenAdapter = null as unknown as ScreenAdapter;
  9. onLoad()
  10. {
  11. if (ScreenAdapter.instance === null) {
  12. ScreenAdapter.instance = this;
  13. }
  14. else {
  15. ScreenAdapter.instance.destroy();
  16. return;
  17. }
  18. console.log("屏幕适配组件加载!", screen, screen.devicePixelRatio, screen.resolution, screen.windowSize, screen.windowSize.width, screen.windowSize.height);
  19. //获取当前平台(设备)显示的有效分辨率(宽、高)
  20. let deviceScreenW = screen.windowSize.width;
  21. let deviceScreenH = screen.windowSize.height;
  22. //获取当前节点(Canvas)变换组件,用于节点尺寸的获取和屏幕适配的设置
  23. let _transform = this.getComponent(UITransform);
  24. //获取当前节点(Canvas)的宽高尺寸
  25. let nodeCurW = _transform.contentSize.width;
  26. let nodeCurH = _transform.contentSize.height;
  27. //通过平台(设备)与节点的宽高比例获取最小值-即
  28. let srcScaleForShowAll = Math.min(deviceScreenW / nodeCurW, deviceScreenH / nodeCurH);
  29. console.log("当前最小缩放", srcScaleForShowAll);
  30. let realWidth = nodeCurW * srcScaleForShowAll;
  31. let realHeight = nodeCurH * srcScaleForShowAll;
  32. console.log(`计算后的尺寸${nodeCurW * (deviceScreenW / realWidth)}, ${nodeCurH * (deviceScreenH / realHeight)}`);
  33. // 2. 基于第一步的数据,再做节点宽高适配
  34. _transform.setContentSize(nodeCurW * (deviceScreenW / realWidth),nodeCurH * (deviceScreenH / realHeight))
  35. // // 3. 因为本节点的宽高发生了改变,所以要手动更新剩下子节点的宽高
  36. this._updateAllChildNodeWidget(this.node);
  37. console.log(`适配尺寸数据详情:视图[${deviceScreenW}, ${deviceScreenH}],缩放[系数-${srcScaleForShowAll},比例-${realWidth}, ${realHeight}],实际尺寸[${_transform.contentSize.width}, ${_transform.contentSize.height}]`)
  38. // if (CC_DEBUG) {
  39. // cc.log(`节点在SHOW_ALL模式下展示的宽高: ${realWidth} x ${realHeight}`);
  40. // cc.log(`节点在SHOW_ALL模式下展示的缩放: ${srcScaleForShowAll}`);
  41. // cc.log(
  42. // `节点在SHOW_ALL模式下做全屏处理后的实际宽高(${cc.view.getCanvasSize().width}x${
  43. // cc.view.getCanvasSize().height
  44. // })等价于于原节点的宽高(${this.node.width}x${this.node.height})`
  45. // );
  46. // }
  47. }
  48. private _updateAllChildNodeWidget(node: Node) {
  49. if (node == null) {
  50. return;
  51. }
  52. let widget = node.getComponent(Widget);
  53. if (widget != null) {
  54. widget.updateAlignment();
  55. }
  56. if (node.children.length == 0) {
  57. return;
  58. }
  59. node.children.forEach((childNode: Node) => {
  60. this._updateAllChildNodeWidget(childNode);
  61. });
  62. }
  63. }