我正在尝试将大图像加载到 MTLTexture 中,它可以处理 4000x6000 图像。但是当我尝试使用 6000x8000 时它不能。
func setTexture(device: MTLDevice, imageName: String) -> MTLTexture? { let textureLoader = MTKTextureLoader(device: device)
var texture: MTLTexture? = nil
// In iOS 10 the origin was changed.
let textureLoaderOptions: [MTKTextureLoader.Option: Any]
if #available(iOS 10.0, *) {
let origin = MTKTextureLoader.Origin.bottomLeft.rawValue
textureLoaderOptions = [MTKTextureLoader.Option.origin : origin]
} else {
textureLoaderOptions = [:]
}
if let textureURL = Bundle.main.url(forResource: imageName, withExtension: nil, subdirectory: "Images") {
do {
texture = try textureLoader.newTexture(URL: textureURL, options: textureLoaderOptions)
} catch {
print("Texture not created.")
}
}
return texture
}
非常基本的代码。我在配备 A9 芯片、GPU 系列 3 的 iPad Pro 上运行它。它应该可以处理这么大的纹理。如果它不接受这个尺寸,我应该以某种方式手动平铺它吗?在这种情况下,最好的方法是什么:使用 MTLRegionMake 复制字节,在 Core Image 或 Core Graphics 上下文中切片......
我感谢任何帮助
根据您的有用评论,我决定手动将其加载到 CGContext 并复制到 MTLTexture。我正在添加下面的解决方案代码。不应在每次创建纹理时都创建上下文,最好将其放在函数之外并继续重用它。
// Grab the CGImage, w = width, h = height...
let context = CGContext(data: nil, width: w, height: h, bitsPerComponent: bpc, bytesPerRow: (bpp / 8) * w, space: colorSpace!, bitmapInfo: bitmapInfo.rawValue)
let flip = CGAffineTransform(a: 1, b: 0, c: 0, d: -1, tx: 0, ty: CGFloat(h))
context?.concatenate(flip)
context?.draw(cgImage, in: CGRect(x: 0, y: 0, width: CGFloat(w), height: CGFloat(h)))
let textureDescriptor = MTLTextureDescriptor()
textureDescriptor.pixelFormat = .rgba8Unorm
textureDescriptor.width = w
textureDescriptor.height = h
guard let data = context?.data else {print("No data in context."); return nil}
let texture = device.makeTexture(descriptor: textureDescriptor)
texture?.replace(region: MTLRegionMake2D(0, 0, w, h), mipmapLevel: 0, withBytes: data, bytesPerRow: 4 * w)
return texture
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句