使用阴影设置从UIView生成图像

时间:2019-06-13 08:15:09

标签: ios uiview uiimage shadow snapshot

我正在尝试生成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];

但是,生成图像的阴影部分模糊。

snapshot

如何像第一个一样获得清晰的图像?

1 个答案:

答案 0 :(得分:0)

在挖掘项目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];