I am taking a screenshot of some UIButtons which are circles about 500 width and 500 height. Since the screenshot can only be made in square form, and I didn't wan't white corners around the image I used this code:
UIGraphicsBeginImageContext(self.Button3.layer.bounds.size);
[self.Button3.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage* image2 = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
NSData* data = UIImagePNGRepresentation(image);
[data writeToFile:BusinessCardPath atomically:YES];
This works perfectly, it returns me a photo of only the circle without white corners. But it can' be enlarged as it will lose pixels, and it doesn't include in the shot all elements such as UILabels that are over the UIButton, but not a subview of the UIButton.
If I use this code:
CGSize imageSize = CGSizeMake(310, 310);
UIGraphicsBeginImageContext(self.Button3.layer.bounds.size);
CGContextRef context = UIGraphicsGetCurrentContext();
/*CGContextTranslateCTM(context, -5, -50);*/
// Iterate over every window from back to front
for (UIWindow *window in [[UIApplication sharedApplication] windows])
{
if (![window respondsToSelector:@selector(screen)] || [window screen] == [UIScreen mainScreen])
{
// -renderInContext: renders in the coordinate space of the layer,
// so we must first apply the layer's geometry to the graphics context
CGContextSaveGState(context);
// Center the context around the window's anchor point
CGContextTranslateCTM(context, [window center].x, [window center].y);
// Apply the window's transform about the anchor point
CGContextConcatCTM(context, [window transform]);
// Offset by the portion of the bounds left of and above the anchor point
CGContextTranslateCTM(context,
-[window bounds].size.width * [[window layer] anchorPoint].x,
-[window bounds].size.height * [[window layer] anchorPoint].y);
// Render the layer hierarchy to the current context
[[window layer] renderInContext:context];
// Restore the context
CGContextRestoreGState(context);
}
}
// Retrieve the screenshot image
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
...I get the opposite effect. Elements above are included in the screenshot, high resolution, but the white corners around the image are there.