// // ViewController.m // screenShotDemo // // Created by kingsoft on 2025/8/7. // #import "ViewController.h" #import "WebKit/WebKit.h" @interface ViewController () @property (nonatomic, strong) UIImageView *snapShotImageView; @property (nonatomic,strong) WKWebView *webviw; @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view. self.view.backgroundColor = [UIColor redColor]; WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init]; self.webviw = [[WKWebView alloc] initWithFrame:self.view.frame configuration:config]; self.webviw.navigationDelegate = self; self.webviw.UIDelegate = self; [self.view addSubview:self.webviw]; UIButton *checkBrn = [UIButton buttonWithType:UIButtonTypeCustom]; [checkBrn setTitle:@"snapshot" forState:UIControlStateNormal]; checkBrn.frame = CGRectMake(60, 200, 120, 40); [checkBrn setTitleColor:[UIColor redColor] forState:UIControlStateNormal]; [checkBrn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside]; [self.view addSubview:checkBrn]; UIImageView *imageView = [[UIImageView alloc] init]; imageView.frame = CGRectMake(60, 250, 200, 200); imageView.layer.borderWidth = 2.0; imageView.layer.borderColor = [UIColor redColor].CGColor; [self.view addSubview:imageView]; self.snapShotImageView = imageView; [self.webviw loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"https:www.baidu.com"]]]; } - (void)btnClick:(id)sender { CGRect rect = CGRectMake(0, 450, 200, 200); UIImage *img = [self screenshotWithRect:rect inView:self.view]; self.snapShotImageView.image = img; } - (UIImage *)screenshotWithRect:(CGRect)rect inView:(UIView *)view { CGRect imgBounds = CGRectMake(0, 0, rect.size.width, rect.size.height); UIGraphicsImageRendererFormat *imgFormat = [[UIGraphicsImageRendererFormat alloc] init]; imgFormat.opaque = YES; imgFormat.scale = UIScreen.mainScreen.scale; UIGraphicsImageRenderer *renderer = [[UIGraphicsImageRenderer alloc] initWithBounds:imgBounds format:imgFormat]; UIImage *theImage = [renderer imageWithActions:^(UIGraphicsImageRendererContext *context) { CGContextRef ctx = context.CGContext; //偏移原点 CGContextTranslateCTM(ctx, -rect.origin.x, -rect.origin.y); CGContextSaveGState(ctx); CGContextTranslateCTM(ctx, view.center.x, view.center.y); CGContextConcatCTM(ctx, [view transform]); CGContextTranslateCTM(ctx, -view.bounds.size.width * view.layer.anchorPoint.x, -view.bounds.size.height * view.layer.anchorPoint.y); [view.layer renderInContext:ctx]; CGContextRestoreGState(ctx); }]; return theImage; } #pragma mark - WKUIDelegate - (void)webView:(WKWebView *)webView runJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(nullable NSString *)defaultText initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(NSString * _Nullable result))completionHandler { } @end