zoom.js 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. cc.Class({
  2. extends: cc.Component,
  3. properties: {
  4. maskNode: cc.Node,
  5. picNode: cc.Node,
  6. },
  7. onLoad () {
  8. this.node.on('touchstart', this.onTouchStart, this);
  9. this.node.on('touchmove', this.onTouchMove, this);
  10. },
  11. // Zoom.js
  12. onTouchStart (event) {
  13. let touches = event.getTouches();
  14. if (touches.length == 1) {
  15. // 一根手指是移动,这里不用写任何代码
  16. }
  17. else if (touches.length == 2) {
  18. this.startPos1 = this.node.convertToNodeSpaceAR(touches[0].getLocation());
  19. this.startPos2 = this.node.convertToNodeSpaceAR(touches[1].getLocation());
  20. this.pointsDis = this.startPos1.sub(this.startPos2).mag();
  21. }
  22. },
  23. // Zoom.js
  24. onTouchMove (event) {
  25. let touches = event.getTouches();
  26. if (touches.length == 1) {
  27. // 一根手指是移动
  28. let delta = event.getDelta();
  29. this.picNode.setPosition(this.picNode.position.add(delta));
  30. this.restrictPic();
  31. }
  32. else if (touches.length == 2) {
  33. // 两根手指是缩放
  34. let touchPoint1 = this.node.convertToNodeSpaceAR(touches[0].getLocation());
  35. let touchPoint2 = this.node.convertToNodeSpaceAR(touches[1].getLocation());
  36. let newPointsDis = touchPoint1.sub(touchPoint2).mag();
  37. if (!this.pointsDis) // 该行代码针对安卓手机
  38. this.pointsDis = 0;
  39. if (newPointsDis > this.pointsDis) {
  40. // 表明两根手指在往外划
  41. this.pointsDis = newPointsDis;
  42. this.picNode.scale += 0.05;
  43. }
  44. else if (newPointsDis < this.pointsDis) {
  45. // 表明两根手指在往内划
  46. if (this.picNode.scale <= 1) {
  47. this.picNode.scale = 1;
  48. return;
  49. }
  50. this.pointsDis = newPointsDis;
  51. this.picNode.scale -= 0.05;
  52. }
  53. this.restrictPic();
  54. }
  55. },
  56. // Zoom.js
  57. restrictPic () {
  58. // 限制移动,放置出现黑边
  59. let picWidth = this.picNode.getBoundingBox().width;
  60. let picHeight = this.picNode.getBoundingBox().height;
  61. if (this.picNode.x>0 && this.picNode.x-0>picWidth/2-this.maskNode.width/2)
  62. this.picNode.x = picWidth/2-this.maskNode.width/2;
  63. if (this.picNode.x<0 && this.picNode.x-0<this.maskNode.width/2-picWidth/2)
  64. this.picNode.x = this.maskNode.width/2-picWidth/2;
  65. if (this.picNode.y>0 && this.picNode.y-0>picHeight/2-this.maskNode.height/2)
  66. this.picNode.y = picHeight/2-this.maskNode.height/2;
  67. if (this.picNode.y<0 && this.picNode.y-0<this.maskNode.height/2-picHeight/2)
  68. this.picNode.y = this.maskNode.height/2-picHeight/2;
  69. }
  70. });