Search code examples
swiftmetalalphamtkview

Alpha / Transparency & MTKView?


I have a Metal fragment shader that returns some transparent colors with an alpha channel and I'd like to reveal a UIView under the MTKView, but they only background result I get is black and "error noise".

MTLRenderPipelineDescriptor:

pipelineStateDescriptor.isAlphaToCoverageEnabled = true
pipelineStateDescriptor.colorAttachments[0].pixelFormat = .bgra8Unorm
pipelineStateDescriptor.colorAttachments[0].isBlendingEnabled = true
pipelineStateDescriptor.colorAttachments[0].destinationRGBBlendFactor = .oneMinusSourceAlpha
pipelineStateDescriptor.colorAttachments[0].destinationAlphaBlendFactor = .oneMinusSourceAlpha

MTLRenderPassDescriptor:

renderPassDescriptor.colorAttachments[0].loadAction = .clear
renderPassDescriptor.colorAttachments[0].clearColor = MTLClearColor(red: 0, green: 0, blue: 0, alpha: 0)

If I change the clear color I can see it under the transparent colors, tho if I skip the clear color I see "error noise". Does the clear color alpha channel actually do anything?

Does anyone know how to make a MTKView transparent?

Update:

Here's the magical property to make a MTKView transparent:

self.isOpaque = false

Solution

  • If a UIView may have transparent content or otherwise fail to fill itself with opaque drawing, then it should set its opaque (isOpaque) property to false so that it will be properly composited with whatever is behind it. Since, MTKView is a subclass of UIView, this applies to it as well.