gpt4 book ai didi

ios - UIGraphicsBeginImageContextWithOptions 不捕获阴影/渐变

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:41:28 30 4
gpt4 key购买 nike

问题

我正在使用 UIGraphicsBeginImageContextWithOptions 将屏幕截图保存到 UIImage 中。虽然这有效,但生成的 UIImage 缺少任何阴影和渐变。

如何让它同时对图层内容进行截图?


显示问题的测试代码


#import "ViewController.h"
#import <QuartzCore/QuartzCore.h>

@implementation ViewController

- (void)viewDidLoad {
//super
[super viewDidLoad];

//background
self.view.backgroundColor = [UIColor whiteColor];

//container
UIView *container = [[UIView alloc] initWithFrame:CGRectMake(10, 10, 300, 200)];
container.backgroundColor = [UIColor blackColor];
[self.view addSubview:container];

//circle
UIView *circle = [[UIView alloc] initWithFrame:CGRectMake(100, 100, 10, 10)];
circle.backgroundColor = [UIColor whiteColor];
circle.layer.cornerRadius = 5;
circle.layer.shadowColor = [UIColor redColor].CGColor;
circle.layer.shadowOffset = CGSizeZero;
circle.layer.shadowOpacity = 1;
circle.layer.shadowRadius = 10;
circle.layer.shadowPath = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(-10, -10, 30, 30)].CGPath;
[container addSubview:circle];

//screenshot
UIGraphicsBeginImageContextWithOptions(container.bounds.size, container.opaque, 0.0);
[container.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *screenshot = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

//image view
UIImageView *iv = [[UIImageView alloc] initWithFrame:CGRectMake(10, 568-200-20-10, 300, 200)];
iv.image = screenshot;
[self.view addSubview:iv];
}

@end

显示问题的模拟器屏幕截图


顶部区域是原始 View 。底部区域是带有屏幕截图的 UIImageView。

Simulator Screenshot

最佳答案

在这一行中,

UIGraphicsBeginImageContextWithOptions(container.bounds.size, container.opaque, 0.0);

put NO instead of container.opaque

使用这个方法,

- (UIImage *)imageOfView:(UIView *)view
{

if ([[UIScreen mainScreen] respondsToSelector:@selector(scale)]) {
UIGraphicsBeginImageContextWithOptions(view.bounds.size, NO, 0.0);
} else {
UIGraphicsBeginImageContext(view.bounds.size);
}

[view.layer renderInContext:UIGraphicsGetCurrentContext()];

UIImage * img = UIGraphicsGetImageFromCurrentImageContext();

UIGraphicsEndImageContext();

return img;
}

关于ios - UIGraphicsBeginImageContextWithOptions 不捕获阴影/渐变,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18940950/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com