swiftavplayermirroringavplayerlayer

How to Mirror(Flip) Video playing using AVPlayer?


I want to Mirror (Flip) video playing using AVPlayer. Like : MirrorTube :- https://chrome.google.com/webstore/detail/mirrortube/olomckflnlligkboahmaihmeaffjdbfm/related?hl=en

i want to achieve same functionality.

I have tried to change CGAffineTransform but it does not work same.

Thanks in advance!


Solution

  • Here's an example how to flip the player vertically and horizontally by using CGAffineTransform:

    PlayerView:

    import AVKit
    
    class PlayerView: UIView {
        var player: AVPlayer? {
            get {
                return playerLayer.player
            }
            set {
                playerLayer.player = newValue
            }
        }
    
        var playerLayer: AVPlayerLayer {
            return layer as! AVPlayerLayer
        }
    
        // Override UIView property
        override static var layerClass: AnyClass {
            return AVPlayerLayer.self
        }
    }
    

    ViewController using the playerView defined in xib/storyboard:

    @IBOutlet var playerView: PlayerView!
    
    @IBAction func flipVerticallyBarButtonItemTouched(_ sender: UIBarButtonItem) {
               UIView.animate(withDuration: 0.2) { [unowned self] in
                   self.playerView.transform = self.playerView.transform.concatenating(CGAffineTransform(scaleX: 1, y: -1))
               }
           }
    @IBAction func flipHorizontallyBarButtonItemTouched(_ sender: UIBarButtonItem) {
               UIView.animate(withDuration: 0.2) { [unowned self] in
                self.playerView.transform = self.playerView.transform.concatenating(CGAffineTransform(scaleX: -1, y: 1))
               }
    }