我以前也有類似的問題。以下爲您可能工作作爲一種解決方法:
UIGraphicsBeginImageContextWithOptions(editingView.bounds.size, NO, 0.0);
[editingView.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
注意,你可能會失去一些精度屏幕捕獲,因爲它可以排除模糊,以及一些核心動畫功能。
編輯:
似乎能夠同時與renderInContext
和drawViewHierarchyInRect
問題/權衡。下面的代碼可能是值得一試(從here取供參考):
- (CGContextRef) createBitmapContextOfSize:(CGSize) size {
CGContextRef context = NULL;
CGColorSpaceRef colorSpace;
int bitmapByteCount;
int bitmapBytesPerRow;
bitmapBytesPerRow = (size.width * 4);
bitmapByteCount = (bitmapBytesPerRow * size.height);
colorSpace = CGColorSpaceCreateDeviceRGB();
if (bitmapData != NULL) {
free(bitmapData);
}
bitmapData = malloc(bitmapByteCount);
if (bitmapData == NULL) {
fprintf (stderr, "Memory not allocated!");
return NULL;
}
context = CGBitmapContextCreate (bitmapData,
size.width,
size.height,
8, // bits per component
bitmapBytesPerRow,
colorSpace,
kCGImageAlphaNoneSkipFirst);
CGContextSetAllowsAntialiasing(context,NO);
if (context== NULL) {
free (bitmapData);
fprintf (stderr, "Context not created!");
return NULL;
}
CGColorSpaceRelease(colorSpace);
CGAffineTransform flipVertical = CGAffineTransformMake(1, 0, 0, -1, 0, size.height);
CGContextConcatCTM(context, flipVertical);
return context;
}
然後,你可以這樣做:
CGContextRef context = [self createBitmapContextOfSize:editingView.bounds.size];
[editingView.layer renderInContext:context];
CGImageRef cgImage = CGBitmapContextCreateImage(context);
UIImage* background = [UIImage imageWithCGImage: cgImage];
CGImageRelease(cgImage);
嗨阿蘭·普爾,我嘗試這樣做。但是我無法獲得CAEmitterLayer和UIView的快照。爲此我找到了一些相關的核心動畫,你可以參考這個鏈接快速的想法http://stackoverflow.com/questions/11926690/caemitterlayer-not-rendering-when-renderincontext-of-superlayer-is-called。並請幫助我這個。並請通過我提供的gif鏈接通過 –
這兩個解決方案似乎存在問題/權衡。我已經用可能的選擇更新了我的答案。代碼來自一篇相當古老的文章,所以它可能會或可能不會工作。 –
不適用於me.missing CAEmitterLayer –