Automatic image aspect ratio correction

To automatically crop images in div-image to the expected aspect ratio, use the aspect_correction extension (iOS only). The expected aspect ratio is set by the aspect property of the element:

{
  "type": "image",
  "image_url": "https://example.com/image.png",
  "aspect": {
    "ratio": 1.5
  },
  "extensions": [
    {
      "id": "aspect_correction"
    }
  ]
}

The extension has no parameters. The aspect ratio deviation tolerance is set in the application when the handler is created.

How it works

  • The extension is applied to a div-image element that has the aspect property.
  • The image is cropped if its actual aspect ratio differs from the expected one by more than the tolerance.
  • If the actual aspect ratio is less than expected, the image is cropped by height.
  • If the actual aspect ratio is greater than expected, the image is cropped by width.

Connection

DivKitComponents(
  ...
  extensionHandlers: [
    AspectCorrectionExtensionHandler(aspectTolerance: 0.001)
  ]
)

aspectTolerance is the aspect ratio deviation tolerance. If the actual aspect ratio differs from the expected one by no more than this value, cropping isn't applied. Default: 0.001.

Learn more

You can discuss topics of interest in the DivKit user community in Telegram: https://t.me/divkit_community_en.

DivKit Repository