裁剪和缩放MTLTexture [英] Crop and scale MTLTexture
问题描述
我可以在现有MTLTexture
区域x1/y1/w1/h1
中创建尺寸为w2/h2
的新MTLTexture
吗?
Can I create a new MTLTexture
of dimensions w2/h2
of an existing MTLTexture
region x1/y1/w1/h1
?
PS:我考虑过使用MTLTexture.buffer?.makeTexture
,但是偏移量必须为64个字节.为什么?
PS: I thought about using MTLTexture.buffer?.makeTexture
but the offset needs to be 64 bytes. Why?
推荐答案
下面是使用MPSImageLanczosScale
进行此操作的示例.请注意,sourceRegion
是在源纹理的像素坐标系中表示的,并且destRegion
应该等于目标纹理的整个面积(请注意,它不专门考虑目标区域的原点):
Here's an example of how you might do this with MPSImageLanczosScale
. Note that sourceRegion
is expressed in the pixel coordinate system of the source texture, and destRegion
should be equal to the full area of the destination texture (note that it specifically doesn't account for the origin of the destination region):
let scaleX = Double(destRegion.size.width) / Double(sourceRegion.size.width)
let scaleY = Double(destRegion.size.height) / Double(sourceRegion.size.height)
let translateX = Double(-sourceRegion.origin.x) * scaleX
let translateY = Double(-sourceRegion.origin.y) * scaleY
let filter = MPSImageLanczosScale(device: device)
var transform = MPSScaleTransform(scaleX: scaleX, scaleY: scaleY, translateX: translateX, translateY: translateY)
let commandBuffer = commandQueue.makeCommandBuffer()
withUnsafePointer(to: &transform) { (transformPtr: UnsafePointer<MPSScaleTransform>) -> () in
filter.scaleTransform = transformPtr
filter.encode(commandBuffer: commandBuffer, sourceTexture: sourceTexture, destinationTexture: destTexture)
}
commandBuffer.commit()
commandBuffer.waitUntilCompleted()
如果需要读取CPU上的目标纹理,则可以等待命令缓冲区完成,或者在完成重采样工作后将完成的处理程序添加到命令缓冲区以接收异步回调.否则,您可以在命令缓冲区中编码其他工作,并立即使用目标纹理.如果要重复缩放纹理,则应该保留一个MPSImageLanczosScale
实例,而不是重复创建它的实例.
If you need to read the destination texture on the CPU, you can wait until the command buffer completes, or add a completed handler to the command buffer to receive an async callback when the resampling work is done. Otherwise, you can encode additional work in the command buffer and use the destination texture immediately. If you're going to be repeatedly scaling textures, you should keep a single instance of MPSImageLanczosScale
around instead of repeatedly creating instances of it.
这篇关于裁剪和缩放MTLTexture的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!