ui_ResolutionAutoFit.ts 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. import { _decorator, Component, Node, size, Size, view,screen, ResolutionPolicy} from 'cc';
  2. const { ccclass, property } = _decorator;
  3. const CHECK_INTERVAL = 0.1;
  4. @ccclass('ch.ResolutionAutoFit')
  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. }