0

基本上,我正在寻找一种从 XIB 附加自定义 UIView 的方法,以便它可以用作 UILabel 中的链接预览。我会选择将 UIView 转换为 UIImage,因为图像可以在 NSTextAttachment 中使用,而后者又可以在 NSAttributedString 中使用。

我正在尝试从此 UIView 获取图像。代码如下:

UIView *preView = [[[NSBundle bundleForClass:[self class]] loadNibNamed:@"LinkPreview" owner:self options:nil] firstObject];

//preView contains 3 labels and 1 imageview with hardcoded values for testing 

if(preView)
{
      preView.bounds = CGRectMake(0,0,400,200);
      NSTextAttachment *attachment = [[NSTextAttachment alloc] init];
      attachment.image = [preView snapShot];
      .
      .
}

方法 snapShot 在 UIView 类别中定义:

#import "UIView+Snapshot.h"
#import <QuartzCore/QuartzCore.h>

@implementation UIView (Snapshot)

-(UIImage *)snapShot
{
    UIGraphicsBeginImageContextWithOptions(self.bounds.size, self.opaque, 0.0f);
    [self drawViewHierarchyInRect:self.bounds afterScreenUpdates:YES];
    UIImage * snapshotImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return snapshotImage;
}

@end

此代码返回给我黑色背景的空图像。

更新 1:preView 很好

在此处输入图像描述

请帮忙。

4

1 回答 1

0

您的视图尚未添加到视图层次结构中。表示它尚未渲染。因此,您将获得黑色图像。

仅出于测试目的,将其添加为当前视图的子视图,然后进行快照。它肯定会奏效。

更新 :

如果您需要快照而不将其添加到层次结构中,请尝试此操作

-(UIImage *)snapShot
{
    UIGraphicsBeginImageContextWithOptions(self.bounds.size, self.opaque, 0.0f);
    [self.layer renderInContext: UIGraphicsGetCurrentContext()];
    UIImage * snapshotImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return snapshotImage;
}

参考:不显示视图的屏幕截图

于 2018-02-13T14:15:32.897 回答