Контактний аркуш
Мета. Розкласти шість плиток сіткою 3 × 2 на одному зображенні, для стрічки попереднього перегляду чи дошки порівняння. Вхідні дані: scene.png. Потрібно: Hokusai 2.2.2.
let positions: [ResizePosition] = [.west, .center, .east, .attention, .entropy, .northEast]let cell = 220, gap = 12, columns = 3
// A blank paper-coloured canvas the size of the grid: one pixel, enlarged.let rows = (positions.count + columns - 1) / columnslet canvas = try Hokusai(raw: Data([248, 242, 230]), width: 1, height: 1, format: .rgb8) .resize(width: gap + columns * (cell + gap), height: gap + rows * (cell + gap), fit: .fill, kernel: .nearest)
// Each cell is the same photo cropped differently; place them with plain arithmetic.let source = try Hokusai(url: URL(fileURLWithPath: "scene.png"))var layers: [CompositeLayer] = []for (index, position) in positions.enumerated() { let tile = try source.resize(width: cell, height: cell, fit: .cover, position: position) layers.append(CompositeLayer(tile, x: gap + (index % columns) * (cell + gap), y: gap + (index / columns) * (cell + gap)))}try await canvas.composite(layers).webp(quality: 85).write(to: URL(fileURLWithPath: "sheet.webp"))
sheet.webpWEBP · 708 × 476 · 22 KB
Як це працює
Section titled “Як це працює”- Порожнє полотно будується з одного пікселя кольору паперу, збільшеного через
resize(fit: .fill, kernel: .nearest)до розміру сітки:gap + columns × (cell + gap)завширшки й так само для рядків. - Кожна плитка — це те саме джерело, змінене до квадрата 220 пікселів з іншою
position, тож сітка заодно порівнює обрізання.west,.center,.east,.attention,.entropyі.northEast(позиція resize). - Один виклик
compositeрозміщує всі плитки черезCompositeLayer(tile, x:y:)за простою арифметикою (gap + column × (cell + gap)). Усі шари змішуються однією нативною операцією.