iosmetalcore-imagemetalkitciimage

Specify sampling method in Metal Core Image Kernel


In Metal we can create samplers like this

      constexpr sampler s(coord::normalized, address::clamp_to_edge, filter::linear);

Then we can sample any texture using this sampler.

I am wondering if something similar is available in Metal Core Image Kernels or not.


Solution

  • Yes, there is! You can use a CISampler that you can pass to your kernel instead of a CIImage:

    let sampler = CISampler(image: image, options: [
        kCISamplerWrapMode: kCISamplerWrapClamp,
        kCISamplerFilterMode: kCISamplerFilterLinear
    ])
    

    You can also set kCISamplerAffineMatrix in the options to define a transform that is applied to the coordinates when sampling (normalized is the default behavior, I think).

    Alternatively, you can use these convenience helpers on CIImage to set the wrap and filter modes:

    // for linear & clamp-to-edge
    let newImage = image.samplingLinear().clampedToExtent()
    // for nearest & clamp-to-black (actually transparent, not black)
    let newImage = image.samplingNearest().cropped(to: aRect)
    

    Using these methods you can also force built-in filters to use the corresponding modes.