Metal之fragment颜色透明和半透明

descriptor.colorAttachments[0].pixelFormat = .bgra8Unorm

pipelineState的像素格式设置为 bgra8Unorm 后,就可以在Shaderfragment返回的float4中按(r, g, b, a) 来描述像素的颜色值。

而其中 a 代表 alpha,也就是透明的意思。

alpha通道通常是用来表示颜色的透明度或者这个像素的可见性(RGBA表示一个像素的话,color.a就是Alpha通道)。

一、透明 discard_fragment

fragment float4 anchorGeometryFragmentLighting(ColorInOut in [[stage_in]],
                                               const float2 coords [[point_coord]],
                                               constant SharedUniforms &uniforms [[ buffer(kBufferIndexSharedUniforms) ]]) {
    const float distSquared = length_squared(coords - float2(0.5));
    if (in.color.a == 0 || distSquared > 0.25) {
        discard_fragment();
    }
    return in.color;
}

discard_fragment 就会直接丢弃当前的片元。

二、半透明 alpha混合

另一种渲染方法是 alpha 混合。 下面的混合方程是将原像素和目标像素做alpha混合。一般渲染这种半透明的表面都是按离相机的距离由远到近进行渲染。

需要先在 pipelinedescriptor开启混合isBlendingEnabled属性,这个属性默认是关闭的,像UIView中渲染一样,混合渲染会影响性能

        descriptor.colorAttachments[0].isBlendingEnabled = true
        descriptor.colorAttachments[0].pixelFormat = renderDestination.colorPixelFormat
        descriptor.colorAttachments[0].rgbBlendOperation = .add
        descriptor.colorAttachments[0].alphaBlendOperation = .add
        descriptor.colorAttachments[0].sourceRGBBlendFactor = .sourceAlpha
        descriptor.colorAttachments[0].sourceAlphaBlendFactor = .sourceAlpha
        descriptor.colorAttachments[0].destinationRGBBlendFactor = .oneMinusSourceAlpha
        descriptor.colorAttachments[0].destinationAlphaBlendFactor = .oneMinusSourceAlpha

开启后,就可以在fragment中,返回如 (1, 0, 0, 0.5) 的颜色值。会渲染出半透明的红色。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章