Last active
May 7, 2022 18:20
-
-
Save PimCoumans/779222872dafe7f570f80148c6251dcf to your computer and use it in GitHub Desktop.
Video aspect transform resizing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// let targetSize = CGSize(width: 100, height: 100) // whatever you want | |
var transform = videoAssetTrack.preferredTransform | |
let naturalSize = videoAssetTrack.naturalSize | |
let videoSize = CGRect(origin: .zero, size: naturalSize).applying(videoAssetTrack.preferredTransform).size | |
let rotation = atan2(transform.b, transform.a) | |
let isRotated = rotation.remainder(dividingBy: .pi) > 0.01 | |
let offset = CGPoint.zero.applying(transform.inverted()) | |
if videoSize != targetSize { | |
// move back to rotation point if rotated | |
transform = transform.translatedBy(x: offset, y: offset) | |
let scale = CGSize(width: targetSize.width / videoSize.width, height: targetSize.height / videoSize.height) | |
let maxScale = max(scale.width, scale.height) | |
let scaledSize = videoSize * maxScale | |
transform = transform.scaledBy(x: maxScale, y: maxScale) | |
let scale = CGSize(width: targetSize.width / videoSize.width, height: targetSize.height / videoSize.height) | |
let maxScale = max(scale.width, scale.height) | |
let scaledSize = videoSize * maxScale | |
transform = transform.scaledBy(x: maxScale, y: maxScale) | |
// return to correct rotation offset | |
transform = transform.translatedBy(x: -offset.x, y: -offset.y) | |
var aspectOffset: CGPoint = .zero | |
if scaledSize.width > targetSize.width { | |
aspectOffset.x = -((scaledSize.width - targetSize.width) / 2) / maxScale | |
} else if scaledSize.height > targetSize.height { | |
aspectOffset.y = -((scaledSize.height - targetSize.height) / 2) / maxScale | |
} | |
if isRotated { | |
transform = transform.translatedBy(x: aspectOffset.y, y: aspectOffset.x) | |
} else { | |
transform = transform.translatedBy(x: aspectOffset.x, y: aspectOffset.y) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment