image-preview.component.ts 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. import { CommonModule } from '@angular/common';
  2. import { Component, Input, OnInit, AfterViewInit, ElementRef, ViewChild, ChangeDetectorRef } from '@angular/core';
  3. import { GestureController, Gesture, IonicModule } from '@ionic/angular';
  4. @Component({
  5. selector: 'app-image-preview',
  6. templateUrl: './image-preview.component.html',
  7. styleUrls: ['./image-preview.component.scss'],
  8. standalone: true,
  9. imports: [IonicModule, CommonModule],
  10. })
  11. export class ImagePreviewComponent implements OnInit, AfterViewInit {
  12. @Input() image: string = '';
  13. show: string = 'none';
  14. private gesture: Gesture | undefined;
  15. private scale = 1;
  16. private startX = 0;
  17. private startY = 0;
  18. private currentX = 0;
  19. private currentY = 0;
  20. // @ViewChild('image-container', { static: true }) imageContainer!: ElementRef;
  21. constructor(private gestureCtrl: GestureController,private cdRef: ChangeDetectorRef) {}
  22. ngOnInit(): void {
  23. // 初始化手势
  24. }
  25. ngAfterViewInit(): void {
  26. this.initGesture();
  27. }
  28. initGesture(): void {
  29. let doc:any = document.getElementById('image-container')
  30. this.gesture = this.gestureCtrl.create({
  31. el: doc,
  32. gestureName: 'pinch-zoom',
  33. threshold: 0,
  34. onStart: (_: any) => {
  35. this.startX = this.currentX;
  36. this.startY = this.currentY;
  37. },
  38. onMove: (ev: any) => {
  39. if(ev.scale) this.scale = Math.max(1, Math.min(3, ev.scale));
  40. this.currentX = this.startX + ev.deltaX;
  41. this.currentY = this.startY + ev.deltaY;
  42. this.cdRef.detectChanges();
  43. },
  44. onEnd: () => {
  45. if (this.scale < 1.1) {
  46. this.scale = 1;
  47. this.currentX = 0;
  48. this.currentY = 0;
  49. }
  50. console.log(this.getTransformStyle());
  51. }
  52. });
  53. this.gesture.enable();
  54. }
  55. getTransformStyle(): string {
  56. return `scale(${this.scale}) translateX(${this.currentX}px) translateY(${this.currentY}px)`;
  57. }
  58. close(){
  59. this.show = 'none'
  60. }
  61. }