H5UIAdapt.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. // cc.Class({
  2. // extends: cc.Component,
  3. // properties: {
  4. // },
  5. // // LIFE-CYCLE CALLBACKS:
  6. // onLoad: function () {
  7. // if (cc.sys.platform == cc.sys.MOBILE_BROWSER) {
  8. // var s1 = cc.view.getDesignResolutionSize();
  9. // var s2 = cc.winSize;
  10. // var scale = s2.width / s1.width;
  11. // // this.node.scaleX = scale;
  12. // this.node.scale = scale;
  13. // }
  14. // },
  15. // });
  16. cc.Class({
  17. extends: cc.Component,
  18. properties: {
  19. // 最小缩放比例
  20. minScale: {
  21. default: 0.8,
  22. tooltip: "最小缩放比例"
  23. },
  24. // 最大缩放比例
  25. maxScale: {
  26. default: 1,
  27. tooltip: "最大缩放比例"
  28. },
  29. // 是否启用高度适配
  30. enableHeightAdapt: {
  31. default: true,
  32. tooltip: "是否启用高度适配"
  33. }
  34. },
  35. onLoad: function () {
  36. this.adaptToScreen();
  37. // 监听屏幕尺寸变化
  38. cc.view.on('canvas-resize', this.adaptToScreen, this);
  39. },
  40. onDestroy: function () {
  41. cc.view.off('canvas-resize', this.adaptToScreen, this);
  42. },
  43. adaptToScreen: function () {
  44. if (cc.sys.platform == cc.sys.MOBILE_BROWSER ||
  45. cc.sys.os === cc.sys.OS_IOS ||
  46. cc.sys.os === cc.sys.OS_ANDROID) {
  47. var designSize = cc.view.getDesignResolutionSize();
  48. var winSize = cc.winSize;
  49. // 计算缩放比例(考虑宽度和高度)
  50. var scaleX = winSize.width / designSize.width;
  51. var scaleY = this.enableHeightAdapt ? winSize.height / designSize.height : scaleX;
  52. // 使用较小的比例以确保内容完全显示
  53. var scale = Math.min(scaleX, scaleY);
  54. // 限制缩放范围
  55. scale = Math.max(this.minScale, Math.min(this.maxScale, scale));
  56. this.node.scale = scale;
  57. }
  58. }
  59. });