ResolutionAutoFit.ts 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. import { _decorator, Component, view, screen, Size, size, ResolutionPolicy } from 'cc';
  2. const { ccclass, property } = _decorator;
  3. const CHECK_INTERVAL = 0.1;
  4. @ccclass('tgxResolutionAutoFit')
  5. export class ResolutionAutoFit extends Component {
  6. private _oldSize: Size = size();
  7. start() {
  8. this.adjustResolutionPolicy();
  9. }
  10. private lastCheckTime = 0;
  11. update(deltaTime: number) {
  12. this.lastCheckTime += deltaTime;
  13. if (this.lastCheckTime < CHECK_INTERVAL) {
  14. return;
  15. }
  16. this.lastCheckTime = 0;
  17. this.adjustResolutionPolicy();
  18. }
  19. adjustResolutionPolicy() {
  20. let winSize = screen.windowSize;
  21. if (!this._oldSize.equals(winSize)) {
  22. let ratio = winSize.width / winSize.height;
  23. let drs = view.getDesignResolutionSize();
  24. let drsRatio = drs.width / drs.height;
  25. if (ratio > drsRatio) {
  26. //wider than desgin. fixed height
  27. view.setResolutionPolicy(ResolutionPolicy.FIXED_HEIGHT);
  28. }
  29. else {
  30. //
  31. view.setResolutionPolicy(ResolutionPolicy.FIXED_WIDTH);
  32. }
  33. this._oldSize.set(winSize);
  34. }
  35. }
  36. }