Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Applying border to image shape

In my application I am having various images of different different shapes. Like tree, cloud. (Sample image is attached). I want to add border to those shapes pro-grammatically. Like if image is of tree then need to highlight tree shape. I cannot use calayer as it will apply border to UIImageView. Can anyone guide me how to achieve this?

sample image

like image 978
Pooja M. Bohora Avatar asked Jan 29 '14 10:01

Pooja M. Bohora


2 Answers

This can be achieved this by using a series of CIFilters. See images corresponding to steps below. In my example base image is a color image with transparent background and mask is black and white.

  1. Use CIEdges to detect edges from the mask.

  2. Then make edges thicker by applying disk maximum filter (CIMorphologyMaximum).

  3. Convert borders image from black-and-white to transparent-and-white with CIMaskToAlpha

  4. Overlay original image on top of borders.

Full code below:

let base = CIImage(cgImage: baseImage.cgImage!)
let mask = CIImage(cgImage: maskImage.cgImage!)
        
// 1
let edges = mask.applyingFilter("CIEdges", parameters: [
   kCIInputIntensityKey: 1.0
])
    
// 2    
let borderWidth = 0.02 * min(baseImage.size.width, baseImage.size.height)
let wideEdges = edges.applyingFilter("CIMorphologyMaximum", parameters: [
    kCIInputRadiusKey: borderWidth
])
        
// 3
let background = wideEdges.applyingFilter("CIMaskToAlpha")
      
// 4  
let composited = base.composited(over: background)
        
// Convert back to UIImage
let context = CIContext(options: nil)
let cgImageRef = context.createCGImage(composited, from: composited.extent)!
return UIImage(cgImage: cgImageRef)

like image 152
nikstar Avatar answered Oct 19 '22 16:10

nikstar


Simple option is to draw the image twice, first with a small scale applied to grow the image a little. Masking if the images aren't transparent (but are black&white).

like image 43
Wain Avatar answered Oct 19 '22 18:10

Wain