25

I would like to know if it is possible to flip the contents of a UIView within the same device; meaning not to an external monitor but on the device itself.

I have searched a bit on google, but all I can find is to external screens.

Suragch
  • 484,302
  • 314
  • 1,365
  • 1,393
Paul Peelen
  • 10,073
  • 15
  • 85
  • 168

2 Answers2

49

You can use CGAffineTransformMakeScale with negative values. Like:

CGAffineTransformMakeScale(1.0, -1.0);

This can be applied on the view by:

//Mirror top to bottom
view.transform = CGAffineTransformMakeScale(1.0, -1.0);

or

//Mirror Left to Right
view.transform = CGAffineTransformMakeScale(-1.0, 1.0);
Mats Stijlaart
  • 5,058
  • 7
  • 42
  • 58
  • what about mirroring a video decompressed and displayed by `AVSampleBufferDisplayLayer` ? left to right? any ideas? Thanks!! – Sam May 29 '19 at 17:11
  • I figured it out :) `_videoLayer.transform = CATransform3DMakeScale(-1.0, 1.0, 1.0);`, in case someone needs to mirror `AVSampleBufferDisplayLayer` – Sam May 29 '19 at 19:26
  • @Sam Thanks this is what I was missing CATransform3DMakeScale(-1.0, 1.0, 1.0) – bojan Mar 29 '21 at 15:43
3

CGAffineTransform is your friend here. Here's some simplified sample code taken form an Xcode Template UIViewController to add a UILabel to a it's view and have that view mirrored. The mirroring is just a side affect of a negative scale. You can do all sorts of things with CGAffineTransform methods, not just limited to scale.

- (void)viewDidLoad;
{
  [super viewDidLoad];

  UILabel *aLabel = [[UILabel alloc] initWithFrame:CGRectZero];
  aLabel.text = @"Sample Text";
  [aLabel sizeToFit];

  //Add it to the center of our UIViewController's View
  CGRect labelFrame = aLabel.frame;
  labelFrame.origin.x = floorf((CGRectGetWidth(self.view.frame) - CGRectGetWidth(labelFrame)) / 2);
  labelFrame.origin.y = floorf((CGRectGetHeight(self.view.frame) - CGRectGetHeight(labelFrame)) / 2);
  aLabel.frame = labelFrame;

  //Mirror the UILabel left to right
  aLabel.transform = CGAffineTransformMakeScale(-1.0, 1.0);

  //OR Mirror the UILabel top to bottom
  //aLabel.transform = CGAffineTransformMakeScale(1.0, -1.0);

  [self.view addSubview:aLabel];
  [aLabel release];
}
murrekatt
  • 5,961
  • 5
  • 39
  • 63
Jessedc
  • 12,320
  • 3
  • 50
  • 63
  • 3
    Shouldn't this be //Mirror the UILabel left to right `aLabel.transform = CGAffineTransformMakeScale(-1.0, 1.0);`? – Kudit Jan 02 '13 at 21:44