自己解决了。
我发现了一个类似的topic https://stackoverflow.com/questions/33844130/take-a-snapshot-of-current-screen-with-metal-in-swift/33903182#33903182.
我为以下几点编写代码。
1:使用Objective-C
2:不使用扩展MTLTexture
- (IBAction)onCapture:(id)sender
{
id<MTLTexture> lastDrawableDisplayed = [metalView.currentDrawable texture];
int width = (int)[lastDrawableDisplayed width];
int height = (int)[lastDrawableDisplayed height];
int rowBytes = width * 4;
int selfturesize = width * height * 4;
void *p = malloc(selfturesize);
[lastDrawableDisplayed getBytes:p bytesPerRow:rowBytes fromRegion:MTLRegionMake2D(0, 0, width, height) mipmapLevel:0];
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGBitmapInfo bitmapInfo = kCGBitmapByteOrder32Little | kCGImageAlphaFirst;
CGDataProviderRef provider = CGDataProviderCreateWithData(nil, p, selfturesize, nil);
CGImageRef cgImageRef = CGImageCreate(width, height, 8, 32, rowBytes, colorSpace, bitmapInfo, provider, nil, true, (CGColorRenderingIntent)kCGRenderingIntentDefault);
UIImage *getImage = [UIImage imageWithCGImage:cgImageRef];
CFRelease(cgImageRef);
free(p);
NSData *pngData = UIImagePNGRepresentation(getImage);
UIImage *pngImage = [UIImage imageWithData:pngData];
UIImageWriteToSavedPhotosAlbum(pngImage, self,
@selector(completeSavedImage:didFinishSavingWithError:contextInfo:), nil);
}
但是,我在 getBytes 方法中收到以下执行错误。
failed assertion `texture must not be a framebufferOnly texture.'
此错误已在以下修复中修复。
因此,我更改了 MTKView 的设置。
metalView.framebufferOnly = false;
Thanks.