Search code examples
iosswiftmetalmetalkit

Texture Reading in Fragment Shader


I am passing a texture to a fragment shader I want to mix the texture color in that pixel value with Blue color Alpha 0.2 How can I do that ?

Fragment Shader

fragment float4 bezier_fragment(VertexOutBezier params[[stage_in]],
                                texture2d<float> texture [[texture(0)]]

VertexOutBezier

struct VertexOutBezier {
    float4 pos[[position]];
    float4 color;

};

Currently I am doing like this but i am getting a error in this shader function in sample. " No matching member function for call to 'sample' " in the line of float canvasColor Initialization

fragment float4 bezier_fragment(VertexOutBezier params[[stage_in]],
                                texture2d<float> texture [[texture(0)]]
                                )
{
    constexpr sampler defaultSampler;
    float4 canvasColor = texture.sample(defaultSampler, params.pos);
    float4 finalColor = mix(canvasColor, params.color, 0.2);
    return finalColor;
}

Solution

  • Replace this line:

    float4 canvasColor = texture.sample(defaultSampler, params.pos);
    

    with

    float4 canvasColor = texture.sample(defaultSampler, params.pos.xy);
    

    2D textures are sampled by 2 coordinates, you provided 4.