BackgroundAdapter.ts 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  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. *
  11. * 1. 将本组件挂载在节点上即可
  12. *
  13. * 注意:
  14. *
  15. * 1. 挂载这个脚本的节点不能加入Widget组件,不然这个适配是没有效果的
  16. * 2. 目前只支持 SHOW_ALL 模式下的背景缩放适配,不支持其他模式的背景缩放
  17. *
  18. * @example
  19. ```
  20. // e.g.
  21. // 代码中设置 SHOW_ALL 模式的参考代码
  22. cc.view.setDesignResolutionSize(720, 1280, cc.ResolutionPolicy.SHOW_ALL);
  23. // 或者 Canvas 组件中,同时勾选 Fit Width 和 Fit Height
  24. ```
  25. */
  26. @ccclass
  27. export default class BackgroundAdapter extends cc.Component {
  28. onLoad() {
  29. // if (CC_DEBUG) {
  30. // cc.log("调整前");
  31. // cc.log(`屏幕分辨率: ${cc.view.getCanvasSize().width} x ${cc.view.getCanvasSize().height}`);
  32. // cc.log(`视图窗口可见区域分辨率: ${cc.view.getVisibleSize().width} x ${cc.view.getVisibleSize().height}`);
  33. // cc.log(`视图中边框尺寸: ${cc.view.getFrameSize().width} x ${cc.view.getFrameSize().height}`);
  34. // cc.log(`设备或浏览器像素比例: ${cc.view.getDevicePixelRatio()}`);
  35. // cc.log(`画布X:设计X=${cc.view.getScaleX()} ,画布Y:设计Y=${cc.view.getScaleY()}`);
  36. // cc.log(`节点宽高: ${this.node.width} x ${this.node.height}`);
  37. // cc.log(`节点缩放: ${this.node.scaleX} x ${this.node.scaleY}`);
  38. // }
  39. // this.node.scale = Math.max(cc.view.getCanvasSize().width / this.node.width, cc.view.getCanvasSize().height / this.node.height);
  40. // 1. 先找到 SHOW_ALL 模式适配之后,本节点的实际宽高以及初始缩放值
  41. let srcScaleForShowAll = Math.min(cc.view.getCanvasSize().width / this.node.width, cc.view.getCanvasSize().height / this.node.height);
  42. let realWidth = this.node.width * srcScaleForShowAll;
  43. let realHeight = this.node.height * srcScaleForShowAll;
  44. // 2. 基于第一步的数据,再做缩放适配
  45. this.node.scale = Math.max(cc.view.getCanvasSize().width / realWidth, cc.view.getCanvasSize().height / realHeight);
  46. // if (CC_DEBUG) {
  47. // cc.log(`节点在SHOW_ALL模式下展示的宽高: ${realWidth} x ${realHeight}`);
  48. // cc.log(`节点在SHOW_ALL模式下展示的缩放: ${srcScaleForShowAll}`);
  49. // cc.log(`节点在SHOW_ALL模式下还需要进行的缩放: ${this.node.scale} 才能达到全屏`);
  50. // }
  51. }
  52. }