我只需要创建一个透明纹理。(带有 alpha 0 的像素)。
func layerTexture()-> MTLTexture {
let width = Int(self.drawableSize.width )
let height = Int(self.drawableSize.height )
let texDescriptor = MTLTextureDescriptor.texture2DDescriptor(pixelFormat: .bgra8Unorm, width: width , height: height, mipmapped: false)
let temparyTexture = self.device?.makeTexture(descriptor: texDescriptor)
return temparyTexture!
}
当我使用预览打开 temparyTexture 时,它似乎是黑色的。这里缺少什么?
更新
我只是尝试使用透明图像创建纹理。代码。
func layerTexture(imageData:Data)-> MTLTexture {
let width = Int(self.drawableSize.width )
let height = Int(self.drawableSize.height )
let bytesPerRow = width * 4
let texDescriptor = MTLTextureDescriptor.texture2DDescriptor(pixelFormat: .rgba8Unorm, width: width , height: height, mipmapped: false)
let temparyTexture = self.device?.makeTexture(descriptor: texDescriptor)
let region = MTLRegionMake2D(0, 0, width, height)
imageData.withUnsafeBytes { (u8Ptr: UnsafePointer<UInt8>) in
let rawPtr = UnsafeRawPointer(u8Ptr)
temparyTexture?.replace(region: region, mipmapLevel: 0, withBytes: rawPtr, bytesPerRow: bytesPerRow)
}
return temparyTexture!
}
方法被调用如下
let image = UIImage(named: "layer1.png")!
let imageData = UIImagePNGRepresentation(image)
self.layerTexture(imageData: imageData!)
其中 layer1.png 是一个透明的 png。但即使它在我尝试替换纹理时出现消息“线程 1:EXC_BAD_ACCESS (code=1, address=0x107e8c000)”崩溃。我相信这是因为图像数据是压缩的,而 rawpointer 应该指向未压缩的数据。我该如何解决这个问题?
我是在正确的道路上还是完全在错误的方向上?有没有其他选择。我只需要创建透明纹理。