我使用MTKView
渲染一些三角形。一切都很好,直到我降低颜色的饱和度和不透明度值,使三角形完全透明。使用相同的值创建SwiftUI的Color
显示正确。这只发生在带有"low"的颜色上。饱和度,如果颜色有100%的饱和度(如#FF0000
),它仍然呈现良好,即使只有1%的不透明度。
我注意到如果我改变MTKView
的colorPixelFormat
,结果会改变。所以不确定我是否只需要改变colorPixelFormat
来解决这个问题,在这种情况下,我也不知道哪一个,因为我对图形的知识有限。下面是颜色#FF8888
的示例:
bgra8Unorm
:渲染 的最小不透明度为55%
bgra8Unorm_srgb
:最低77%的不透明度来渲染,颜色比它应该的浅很多。在Swift中,我将颜色存储为[Float]
,在MSL中,它将转换为float4*
。顶点和片段函数没有什么特别的,只是返回输入。这不是很可能的问题在于其他颜色的工作。
一些代码来显示我的设置:
// MTKView's etup
clearColor = MTLClearColor(red: 0, green: 0, blue: 0, alpha: 0)
isOpaque = false
layer.magnificationFilter = .nearest
layer.minificationFilter = .nearest
// State setup
let pipelineDescriptor = MTLRenderPipelineDescriptor()
pipelineDescriptor.vertexFunction = vertexFunction
pipelineDescriptor.fragmentFunction = fragmentFunction
pipelineDescriptor.colorAttachments[0].pixelFormat = .bgra8Unorm
pipelineState = try? device.makeRenderPipelineState(descriptor: pipelineDescriptor)
// draw method setup
guard let vertexBuffer = vertexBuffer,
let indexBuffer = indexBuffer,
let indexCount = indexCount,
let colorBuffer = colorBuffer,
let pipelineState = pipelineState,
let discriptor = view.currentRenderPassDescriptor,
let commandBuffer = commandQueue.makeCommandBuffer(),
let commandEncoder = commandBuffer.makeRenderCommandEncoder(
descriptor: discriptor
),
let drawable = view.currentDrawable else {
return
}
commandEncoder.setRenderPipelineState(pipelineState)
commandEncoder.setVertexBuffer(vertexBuffer, offset: 0, index: 0)
commandEncoder.setVertexBuffer(colorBuffer, offset: 0, index: 1)
commandEncoder.drawIndexedPrimitives(
type: .triangle,
indexCount: indexCount,
indexType: .uint32,
indexBuffer: indexBuffer,
indexBufferOffset: 0
)
commandEncoder.endEncoding()
commandBuffer.present(drawable)
commandBuffer.commit()
找到答案:https://stackoverflow.com/a/51414692/8355412
基本上,我只需要对每个rgb分量进行alpha预乘