3

I have three views on my storyboard, viewA, viewB, viewC.

I’m trying to screen capture only two views as they appear on screen in their current place, viewB and viewC.

The trouble is, when I render them, the resulting image captured shows viewB and viewC in incorrect locations, the position of the views change moving top left (0, 0), see image.

How can I correct the code below so that I can capture the views viewB and viewC exactly as they are positioned on the view using the renderInContext implementation below?

UIGraphicsBeginImageContextWithOptions(self.view.frame.size, false, 0)
self.viewB.layer.renderInContext(UIGraphicsGetCurrentContext()!)
self.viewC.layer.renderInContext(UIGraphicsGetCurrentContext()!)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()

enter image description here

rmaddy
  • 314,917
  • 42
  • 532
  • 579
user4806509
  • 2,925
  • 5
  • 37
  • 72

1 Answers1

5

From the docs for renderInContext::

Renders in the coordinate space of the layer.

Each view's layer has an origin of 0,0 so they each appear in the upper-left corner.

To fix this you need to translate the graphics context by the view's origin before calling renderInContext:.

UIGraphicsBeginImageContextWithOptions(self.view.frame.size, false, 0)
let ctx = UIGraphicsGetCurrentContext()

CGContextSaveGState(ctx)
CGContextTranslateCTM(ctx, self.viewB.frame.origin.x, self.viewB.frame.origin.y)
self.viewB.layer.renderInContext(UIGraphicsGetCurrentContext()!)
CGContextRestoreGState(ctx)

CGContextSaveGState(ctx)
CGContextTranslateCTM(ctx, self.viewC.frame.origin.x, self.viewC.frame.origin.y)
self.viewC.layer.renderInContext(UIGraphicsGetCurrentContext()!)
CGContextRestoreGState(ctx)

let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
rmaddy
  • 314,917
  • 42
  • 532
  • 579
  • Thanks for your reply @rmaddy . How do I "translate the graphics context" specifically? – user4806509 Apr 06 '16 at 03:22
  • 1
    See my update. I believe that is correct. It's not tested. – rmaddy Apr 06 '16 at 03:28
  • Thank you @rmaddy . I've tested that and it works. I had to change the `-self.viewC` to `self.viewC` removing the `-` for it to work. I’ve since added a new view and am having trouble capturing that for some reason, it never shows, I suspect it might be related to auto constraints but not sure why which I’m investigating. – user4806509 Apr 06 '16 at 14:30
  • This answer + https://stackoverflow.com/questions/23110601/position-a-view-for-drawing-via-renderincontext is exactly what is needed. Love SO :-) – byemute Nov 01 '18 at 10:13