UILabel 的屏幕截图以及 UIImageView 中的内容

ScreenShot of an UILabel and what is in a UIImageView

我正在尝试截取我的 UIImageView 和位于其上的 UILabel。

我目前所做的是抓取 ImageView 中的 UIImage,然后在其上渲染叠加层,但 UILabel 的定位完全错误。我将捕获的大小设置为实际图像大小(这不是我想要的)。

我只想截取屏幕上显示的内容。

CGSize imageSize = self.imageFromOtherView.size;
// define the size and grab a UIImage from it
UIGraphicsBeginImageContextWithOptions(imageSize, NO, 0);

[self.imageFromOtherView drawInRect:CGRectMake(0, 0, imageSize.width, imageSize.height)];

[self.socialLabel.layer renderInContext:UIGraphicsGetCurrentContext()];

UIImage *capturedImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

创建一个 UIView 来保存 UIImageView 和 UILabel。然后通过这段代码传递这个容器视图。我的视图是一个名为 viewForPhoto 的 属性,因此当代码被调用时,它只会捕获该视图。您可以调整它以使其接收视图。这将 return 您想要的 UIImage。

- (UIImage *)imageByRenderingView
{
    UIGraphicsBeginImageContextWithOptions(self.viewForPhotoView.bounds.size, NO, 0.0);
    [self.viewForPhotoView.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *resultingImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return resultingImage;
}

将这两个视图添加到公共容器视图,然后在视图上调用 - (BOOL)drawViewHierarchyInRect:(CGRect)rect afterScreenUpdates:(BOOL)afterUpdates 以在上下文中呈现它。