Добавление распознавателя жестов сжатия

Жест сжатия используется для интерактивного масштабирования и реализуется с помощью класса PinchGestureRecognizer. Стандартное назначение жеста сжатия — интерактивное масштабирование изображения в месте сжатия. Для этого изменяется масштаб содержимого в окне просмотра, как показано в этой статье.

Чтобы элемент пользовательского интерфейса можно было масштабировать жестом сжатия, необходимо создать экземпляр PinchGestureRecognizer, реализовать обработку события PinchUpdated и добавить новый распознаватель жестов в коллекцию GestureRecognizers элемента пользовательского интерфейса. В следующем примере кода показан распознаватель PinchGestureRecognizer, присоединенный к элементу Image:

var pinchGesture = new PinchGestureRecognizer();
pinchGesture.PinchUpdated += (s, e) => {
  // Handle the pinch
};
image.GestureRecognizers.Add(pinchGesture);

Реализация в XAML показана в следующем примере кода:

<Image Source="waterfront.jpg">
  <Image.GestureRecognizers>
    <PinchGestureRecognizer PinchUpdated="OnPinchUpdated" />
  </Image.GestureRecognizers>
</Image>

Затем код обработчика событий OnPinchUpdated добавляется в файл кода программной части:

void OnPinchUpdated (object sender, PinchGestureUpdatedEventArgs e)
{
  // Handle the pinch
}

Создание контейнера PinchToZoom

Для выполнения преобразований в пользовательском интерфейсе в ответ на жест сжатия требуется ряд математических операций. В этом разделе представлен универсальный вспомогательный класс для интерактивного масштабирования любого элемента пользовательского интерфейса. Следующий пример кода демонстрирует класс PinchToZoomContainer:

public class PinchToZoomContainer : ContentView
{
  ...

  public PinchToZoomContainer ()
  {
    var pinchGesture = new PinchGestureRecognizer ();
    pinchGesture.PinchUpdated += OnPinchUpdated;
    GestureRecognizers.Add (pinchGesture);
  }

  void OnPinchUpdated (object sender, PinchGestureUpdatedEventArgs e)
  {
    ...
  }
}

Этот класс может служить оболочкой для элемента пользовательского интерфейса, содержимое которого масштабируется в ответ на жест сжатия. В следующем примере кода XAML показан контейнер PinchToZoomContainer, содержащий элемент Image.

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:local="clr-namespace:PinchGesture;assembly=PinchGesture"
             x:Class="PinchGesture.HomePage">
    <ContentPage.Content>
        <Grid Padding="20">
            <local:PinchToZoomContainer>
                <local:PinchToZoomContainer.Content>
                    <Image Source="waterfront.jpg" />
                </local:PinchToZoomContainer.Content>
            </local:PinchToZoomContainer>
        </Grid>
    </ContentPage.Content>
</ContentPage>

В следующем примере кода показано, как элемент Image заключается в контейнер PinchToZoomContainer на странице C#.

public class HomePageCS : ContentPage
{
  public HomePageCS ()
  {
    Content = new Grid {
      Padding = new Thickness (20),
      Children = {
        new PinchToZoomContainer {
          Content = new Image { Source = ImageSource.FromFile ("waterfront.jpg") }
        }
      }
    };
  }
}

Image Когда элемент получает жест скрепления, отображаемое изображение будет увеличиваться или выходить. Масштаб выполняется методомPinchZoomContainer.OnPinchUpdated, который показан в следующем примере кода:

void OnPinchUpdated (object sender, PinchGestureUpdatedEventArgs e)
{
  if (e.Status == GestureStatus.Started) {
    // Store the current scale factor applied to the wrapped user interface element,
    // and zero the components for the center point of the translate transform.
    startScale = Content.Scale;
    Content.AnchorX = 0;
    Content.AnchorY = 0;
  }
  if (e.Status == GestureStatus.Running) {
    // Calculate the scale factor to be applied.
    currentScale += (e.Scale - 1) * startScale;
    currentScale = Math.Max (1, currentScale);

    // The ScaleOrigin is in relative coordinates to the wrapped user interface element,
    // so get the X pixel coordinate.
    double renderedX = Content.X + xOffset;
    double deltaX = renderedX / Width;
    double deltaWidth = Width / (Content.Width * startScale);
    double originX = (e.ScaleOrigin.X - deltaX) * deltaWidth;

    // The ScaleOrigin is in relative coordinates to the wrapped user interface element,
    // so get the Y pixel coordinate.
    double renderedY = Content.Y + yOffset;
    double deltaY = renderedY / Height;
    double deltaHeight = Height / (Content.Height * startScale);
    double originY = (e.ScaleOrigin.Y - deltaY) * deltaHeight;

    // Calculate the transformed element pixel coordinates.
    double targetX = xOffset - (originX * Content.Width) * (currentScale - startScale);
    double targetY = yOffset - (originY * Content.Height) * (currentScale - startScale);

    // Apply translation based on the change in origin.
    Content.TranslationX = targetX.Clamp (-Content.Width * (currentScale - 1), 0);
    Content.TranslationY = targetY.Clamp (-Content.Height * (currentScale - 1), 0);

    // Apply scale factor.
    Content.Scale = currentScale;
  }
  if (e.Status == GestureStatus.Completed) {
    // Store the translation delta's of the wrapped user interface element.
    xOffset = Content.TranslationX;
    yOffset = Content.TranslationY;
  }
}

Этот метод изменяет масштаб элемента пользовательского интерфейса, заключенного в оболочку, в соответствии с жестом сжатия. Масштаб, применяемый в месте сжатия, рассчитывается исходя из значений свойств Scale, ScaleOrigin и Status экземпляра PinchGestureUpdatedEventArgs. После этого заключенный в оболочку элемент интерфейса масштабируется в месте сжатия путем присвоения свойствам TranslationX, TranslationY и Scale вычисленных значений.