基本上,我正在寻找一种从 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 很好
请帮忙。