I have a video that is placed at the origin of the screen, no rotation, as seen in this picture (ignore the background):
I apply a basic rectangle (no rotation for now) crop with setCropRectangle so that it cuts my video in half, and displays the right side as you can see here:
Now, I want to rotate my crop rectangle at 45 degrees. The test code I use looks something like this. I am just applying a rotating transform to my crop rectangle before I use it.
let firstScale = CGFloat(0.8)
let FirstlayerInstruction = AVMutableVideoCompositionLayerInstruction(assetTrack: firstTrack!)
let Scale = CGAffineTransform(scaleX: firstScale, y: firstScale)
let Move = CGAffineTransform(translationX: 0, y: 0)
let Rotation = CGAffineTransform(rotationAngle: 0)
FirstlayerInstruction.setTransform(Scale.concatenating(Rotation).concatenating(Move), at: .zero)
let rectTransform = CGAffineTransform(rotationAngle: 45.degreesToRadians).concatenating(CGAffineTransform(translationX: firstTrack!.naturalSize.width/2, y: 0))
let rect = CGRect(x: 0, y: 0, width: firstTrack!.naturalSize.width/2, height: firstTrack!.naturalSize.height).applying(rectTransform)
FirstlayerInstruction.setCropRectangle(rect, at: .zero)
This is just some test data. You can see I pass 45.degreesToRadians as the rotation of the crop rectangle.
The result I get is not what I was expecting though:
Actual Result + Expected Result
As you can see, the crop rectangle ignores rotation for some reason and keeps a larger, square form, instead of a diamond shape. The same applies for any rotation, negative values, 30, 60, etc. Anything I use for rotating the crop rectangle is not actually rotated.
Is the Core Graphics API limited to doing this? How can I achieve my expected result?
You can not specify the angle of cropping. If you want to clip overlaid video, you have to create your own class
implementing AVVideoCompositing
protocol, and assign it as customVideoCompositorClass
property in your AVMutableVideoComposition
. In this class you can specify a custom way of rendering resulting frame from source pixel buffers.
You can refer to this answer: https://stackoverflow.com/a/28260671/2051369