Trước hết, tôi muốn cảm ơn sergio ... câu trả lời của anh ấy đã khiến tôi bắt đầu nhưng tôi nghĩ tôi sẽ chia sẻ một số mã mà tôi không thấy rõ ràng là tôi phải viết để làm cho nó hoạt động:
Dưới đây là làm thế nào để tạo ra một hình ảnh thu nhỏ cho một trang mà không bao giờ có nó hiển thị:
// Your width and height can be whatever you like, but if you want this to render
// off screen, you need an x and y bigger than the superview's width and height
UIWebView* webView = [[UIWebView alloc] initWithFrame:CGRectMake(largerScreenDimension, largerScreenDimension, largerScreenDimension, largerScreenDimension)];
[self.view addSubview:webView]; // UIWebViews without an assigned superview don't load ever.
webView.delegate = self; // or whoever you have implement UIWebViewDelegate
webView.scalesToFit = YES; // This zooms the page appropriately to fill the entire thumbnail.
[webView loadRequest:[NSURLRequest requestWithURL:url]];
Sau đó thực hiện điều này trong đại biểu của bạn:
- (void)webViewDidFinishLoad:(UIWebView *)webView {
UIGraphicsBeginImageContext(webView.bounds.size);
[webView.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *webViewImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
NSData *thumbnailData = UIImagePNGRepresentation(webViewImage);
[webView removeFromSuperview];
}
Cuối cùng, để hiển thị thumbnail này you'l l cần một cái gì đó như:
thumbnailImageView.image = [UIImage imageWithData:thumbnailData];
Điều tôi sẽ đề cập, tôi muốn tạo nhiều hình thu nhỏ cùng một lúc. Tôi đã tìm thấy sử dụng objc_setAssociatedObject()
và objc_getAssociatedObject()
để rất hữu ích khi theo dõi xem webView nào đang tải hình thu nhỏ nào. Đi sâu vào chi tiết về cách làm việc đó là vượt quá phạm vi của câu hỏi này, mặc dù.
bạn có thích làm điều này trong iOS không? –