Home > other >  How to create a border around an NSImage CIFilter ObjC
How to create a border around an NSImage CIFilter ObjC

Time:08-02

I'm trying to create a stoke border around a PNG with transparent background in an NSImage.

I originally tried duplicating the image and having a larger scale and then using CIFilter to make it white - this works great for shapes like circles and other solid shapes.

However i'll have shapes like the example image below:

Tree Image

With this Image it doesn't work well at all.

I'm thinking that maybe I can do something with CIEdge and CIMorphologyMaximum but i'm not sure if i'm thinking in a good direction - would appreciate some advise if anyone has come across a similar challenge.

CodePudding user response:

Yes, CIMorphologyMaximum should be the way to go. Try this:

import CoreImage.CIFilterBuiltins

let ciImage = ...

// Apply morphology maximum to "erode" image in all direction into transparent area.
let filter = CIFilter.morphologyMaximum()
filter.inputImage = ciImage
filter.radius = 5 // border radius
let eroded = filter.outputImage!

// Turn all pixels of eroded image into desired border color.
let colorized = CIBlendKernel.sourceAtop.apply(foreground: .white, background: eroded)!.cropped(to: eroded.extent)

// Blend original image over eroded, colorized image.
let imageWithBorder = ciImage.composited(over: colorized)

And in Objective-C:

CIImage* ciImage = ...;

// Apply morphology maximum to "erode" image in all direction into transparent area.
CIFilter* erodeFilter = [CIFilter filterWithName:@"CIMorphologyMaximum"];
[erodeFilter setValue:ciImage forKey:kCIInputImageKey];
[erodeFilter setValue:@5 forKey:kCIInputRadiusKey];
CIImage* eroded = erodeFilter.outputImage;

// Turn all pixels of eroded image into desired border color.
CIImage* colorized = [[CIBlendKernel.sourceAtop applyWithForeground:[CIImage whiteImage] background:eroded] imageByCroppingToRect:eroded.extent];

// Blend original image over eroded, colorized image.
CIImage* imageWithBorder = [ciImage imageByCompositingOverImage:colorized];
  • Related