FullScreenBgAutoFit.ts 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. import { _decorator, Component, screen, ResolutionPolicy, Size, size, view, UITransform, Sprite, Canvas } from 'cc';
  2. const { ccclass, property } = _decorator;
  3. const CHECK_INTERVAL = 0.1;
  4. @ccclass('FullScreenBgAutoFit')
  5. export class FullScreenBgAutoFit extends Component {
  6. @property(Canvas) canvasUITrans:UITransform;
  7. private _oldSize:Size = size();
  8. private _originalSize:Size;
  9. private _uiTransform:UITransform;
  10. private _sprite:Sprite;
  11. start() {
  12. this._uiTransform = this.getComponent(UITransform);
  13. this._sprite = this.getComponent(Sprite);
  14. if(!this._uiTransform || !this._sprite){
  15. return;
  16. }
  17. this._originalSize = this._sprite.spriteFrame.originalSize;
  18. this._sprite.sizeMode = Sprite.SizeMode.CUSTOM;
  19. if(!this.canvasUITrans){
  20. let parent = this.node.parent;
  21. while(parent){
  22. let canvas = parent.getComponent(Canvas);
  23. if(canvas){
  24. this.canvasUITrans = canvas.getComponent(UITransform);
  25. break;
  26. }
  27. parent = parent.parent;
  28. }
  29. }
  30. this.adjustResolutionPolicy();
  31. }
  32. private lastCheckTime = 0;
  33. update(deltaTime: number) {
  34. this.lastCheckTime+=deltaTime;
  35. if(this.lastCheckTime < CHECK_INTERVAL){
  36. return;
  37. }
  38. this.lastCheckTime = 0;
  39. this.adjustResolutionPolicy();
  40. }
  41. adjustResolutionPolicy(){
  42. let winSize = this.canvasUITrans.contentSize;
  43. if(!this._oldSize.equals(winSize)){
  44. let ratio = winSize.width / winSize.height;
  45. let imgW2H = this._originalSize.width / this._originalSize.height;
  46. if(ratio > imgW2H){
  47. //wider than desgin.
  48. this._uiTransform.width = winSize.width;
  49. this._uiTransform.height = winSize.width / imgW2H;
  50. }
  51. else{
  52. //higher than desgin.
  53. this._uiTransform.width = winSize.height * imgW2H;
  54. this._uiTransform.height = winSize.height;
  55. }
  56. this._oldSize.set(winSize);
  57. }
  58. }
  59. }