AdaptToScreen.ts 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. import { _decorator, Component, Enum, UITransform, view } from 'cc';
  2. const { ccclass, property } = _decorator;
  3. @ccclass('AdaptToScreen')
  4. export class AdaptToScreen extends Component {
  5. // 增加左右适配选项:Top、Down、Left、Right
  6. @property({ type: Enum({ Top: 0, Down: 1, Left: 2, Right: 3 }) })
  7. public position: number = 0;
  8. @property
  9. public offset: number = 0;
  10. @property
  11. public scale: number = 1;
  12. start() {
  13. this.adaptToScreen();
  14. }
  15. adaptToScreen() {
  16. const screenHeight = view.getVisibleSize().height;
  17. const screenWidth = view.getVisibleSize().width;
  18. console.log(screenHeight, screenWidth);
  19. const uiTransform = this.node.getComponent(UITransform);
  20. // 适配顶部
  21. if (this.position === 0) {
  22. this.node.setPosition(this.node.position.x / this.scale, (screenHeight / 2 - uiTransform.height / 2 - this.offset) / this.scale);
  23. if (mtec.cc.is_long_screen) {
  24. this.node.setPosition(this.node.position.x / this.scale, (this.node.position.y - 100 - this.offset) / this.scale);
  25. }
  26. }
  27. // 适配底部
  28. else if (this.position === 1) {
  29. this.node.setPosition(this.node.position.x / this.scale, (-(screenHeight / 2 - uiTransform.height / 2) + this.offset) / this.scale);
  30. }
  31. // 适配左侧
  32. else if (this.position === 2) {
  33. this.node.setPosition((-(screenWidth / 2 - uiTransform.width / 2) + this.offset) / this.scale, this.node.position.y / this.scale);
  34. }
  35. // 适配右侧
  36. else if (this.position === 3) {
  37. this.node.setPosition((screenWidth / 2 - uiTransform.width / 2 - this.offset) / this.scale, this.node.position.y / this.scale);
  38. }
  39. }
  40. }