使用阴影设置从 UIView 生成图像
Posted
技术标签:
【中文标题】使用阴影设置从 UIView 生成图像【英文标题】:Generate an image from UIView with shadowing settings 【发布时间】:2019-06-13 08:15:09 【问题描述】:我正在尝试生成 UIImage 作为 UIView 的快照。
CGFloat length = 100;
CGFloat radius = 20;
self.bgView = [[UIView alloc] initWithFrame:CGRectMake(100, 100, length, length)];
self.bgView.backgroundColor = [UIColor whiteColor];
self.bgView.layer.cornerRadius = 5;
self.bgView.layer.shadowRadius = radius;
self.bgView.layer.shadowOpacity = 0.95;
self.bgView.layer.shadowColor = [UIColor colorWithRed:1 green:0 blue:0 alpha:0.5].CGColor;
[self.view addSubview:self.bgView];
CGFloat contextLength = length + radius * 2;
UIGraphicsBeginImageContextWithOptions(CGSizeMake(contextLength, contextLength), NO, 0.0);
CGContextTranslateCTM(UIGraphicsGetCurrentContext(), radius, radius);
[self.bgView.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
self.secondBgView = [[UIImageView alloc] initWithFrame:CGRectMake(80, 260, contextLength, contextLength)];
self.secondBgView.image = image;
[self.view addSubview:self.secondBgView];
但是,生成的图像的阴影部分是模糊的。
如何获得和第一个一样清晰的图像?
【问题讨论】:
【参考方案1】:挖掘项目https://github.com/uber/ios-snapshot-test-case
后,发现UIView的drawViewHierarchyInRect:drawViewHierarchyInRect:
有效。
UIView *wrapperView = [[UIView alloc] initWithFrame:CGRectMake(0, 100, 320, 150)];
[wrapperView addSubview:self.bgView];
[self.view addSubview:wrapperView];
// ...
[wrapperView drawViewHierarchyInRect:wrapperView.bounds afterScreenUpdates:YES];
【讨论】:
以上是关于使用阴影设置从 UIView 生成图像的主要内容,如果未能解决你的问题,请参考以下文章