幅500、高さ500の円であるいくつかのUIButtonのスクリーンショットを撮っています。スクリーンショットは正方形でしか作成できず、画像の周りに白い角ができたくないので、次のコードを使用しました。
UIGraphicsBeginImageContext(self.Button3.layer.bounds.size);
[self.Button3.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage* image2 = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
NSData* data = UIImagePNGRepresentation(image);
[data writeToFile:BusinessCardPath atomically:YES];
これは完全に機能します。白い角のない円のみの写真が返されます。ただし、ピクセルが失われるため拡大できます。また、UIButton の上にある UILabels などのすべての要素がショットに含まれているわけではありませんが、UIButton のサブビューは含まれていません。
このコードを使用する場合:
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();
・・・逆効果です。上記の要素は高解像度のスクリーンショットに含まれていますが、画像の周りに白い角があります。