我正在截取一些 UIButtons 的屏幕截图,它们是大约 500 宽和 500 高的圆圈。由于屏幕截图只能以正方形形式制作,并且我不想在图像周围出现白色角落,因此我使用了以下代码:
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 上的 UILabel,但不包括 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();
...我得到相反的效果。上面的元素包含在屏幕截图中,高分辨率,但图像周围的白色角落在那里。