ResolutionAutoFit.ts 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. import { _decorator, Component, find, Node, ResolutionPolicy, screen,Size, size, UITransform, view } from 'cc';
  2. const { ccclass, property } = _decorator;
  3. const CHECK_INTERVAL = 0.1;
  4. @ccclass('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. let splash: Node = find("Canvas/SpriteSplash");
  26. if(splash) {
  27. splash.getComponent(UITransform).contentSize = new Size(drs.width,drs.height);
  28. }
  29. if(ratio > drsRatio){
  30. //wider than desgin. fixed height
  31. view.setResolutionPolicy(ResolutionPolicy.FIXED_HEIGHT);
  32. }
  33. else{
  34. //
  35. view.setResolutionPolicy(ResolutionPolicy.FIXED_WIDTH);
  36. }
  37. this._oldSize.set(winSize);
  38. }
  39. }
  40. }