ContentAdapter.ts 3.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. const { ccclass, property } = cc._decorator;
  2. /**
  3. * @classdesc 游戏主内容节点自适应所有分辨率的脚本
  4. * @author caizhitao
  5. * @version 0.1.0
  6. * @since 2018-11-30
  7. * @description
  8. *
  9. * 用法:
  10. * 1. 将本组件挂载在节点上即可
  11. *
  12. * 适配原理:
  13. * 1. 将游戏主内容节点的宽高调整为画布的大小,以进行Size适配
  14. *
  15. * 注意:
  16. * 1. 挂载这个脚本的节点不能加入Widget组件,不然这个适配是没有效果的
  17. * 2. 目前只支持 SHOW_ALL 模式下的背景缩放适配,不支持其他模式的背景缩放
  18. *
  19. * @example
  20. ```
  21. // e.g.
  22. // 代码中设置 SHOW_ALL 模式的参考代码
  23. cc.view.setDesignResolutionSize(720, 1280, cc.ResolutionPolicy.SHOW_ALL);
  24. // 或者 Canvas 组件中,同时勾选 Fit Width 和 Fit Height
  25. ```
  26. */
  27. @ccclass
  28. export default class ContentAdapter extends cc.Component {
  29. onLoad() {
  30. // if (CC_DEBUG) {
  31. // cc.log("调整前");
  32. // cc.log(`屏幕分辨率: ${cc.view.getCanvasSize().width} x ${cc.view.getCanvasSize().height}`);
  33. // cc.log(`视图窗口可见区域分辨率: ${cc.view.getVisibleSize().width} x ${cc.view.getVisibleSize().height}`);
  34. // cc.log(`视图中边框尺寸: ${cc.view.getFrameSize().width} x ${cc.view.getFrameSize().height}`);
  35. // cc.log(`设备或浏览器像素比例: ${cc.view.getDevicePixelRatio()}`);
  36. // cc.log(`节点宽高: ${this.node.width} x ${this.node.height}`);
  37. // }
  38. // 1. 先找到 SHOW_ALL 模式适配之后,本节点的实际宽高以及初始缩放值
  39. let srcScaleForShowAll = Math.min(cc.view.getCanvasSize().width / this.node.width, cc.view.getCanvasSize().height / this.node.height);
  40. let realWidth = this.node.width * srcScaleForShowAll;
  41. let realHeight = this.node.height * srcScaleForShowAll;
  42. // 2. 基于第一步的数据,再做节点宽高适配
  43. this.node.width = this.node.width * (cc.view.getCanvasSize().width / realWidth);
  44. this.node.height = this.node.height * (cc.view.getCanvasSize().height / realHeight);
  45. // // 3. 因为本节点的宽高发生了改变,所以要手动更新剩下子节点的宽高
  46. // this._updateAllChildNodeWidget(this.node);
  47. // if (CC_DEBUG) {
  48. // cc.log(`节点在SHOW_ALL模式下展示的宽高: ${realWidth} x ${realHeight}`);
  49. // cc.log(`节点在SHOW_ALL模式下展示的缩放: ${srcScaleForShowAll}`);
  50. // cc.log(
  51. // `节点在SHOW_ALL模式下做全屏处理后的实际宽高(${cc.view.getCanvasSize().width}x${
  52. // cc.view.getCanvasSize().height
  53. // })等价于于原节点的宽高(${this.node.width}x${this.node.height})`
  54. // );
  55. // }
  56. }
  57. // private _updateAllChildNodeWidget(parentNode: cc.Node) {
  58. // if (parentNode == null) {
  59. // return;
  60. // }
  61. // let widget = parentNode.getComponent(cc.Widget);
  62. // if (widget != null) {
  63. // widget.updateAlignment();
  64. // }
  65. // if (parentNode.childrenCount == 0) {
  66. // return;
  67. // }
  68. // parentNode.children.forEach((childNode: cc.Node) => {
  69. // this._updateAllChildNodeWidget(childNode);
  70. // });
  71. // }
  72. }