裁剪和缩放MTLTexture [英] Crop and scale MTLTexture

查看:358
本文介绍了裁剪和缩放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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆