simnik
simnik

Reputation: 483

Fill an Image using an ImageMask Swift

I am trying to fiddle out how to fill a PNG which center is transparent with a color. I made you a preview to visualize what I'm not able to explain :D

enter image description here

The "Shield Icon" are only a stroke. The have no background wether on the inside nor on the outside.

I want to call a function like

func fillShield(percentage: CGFLoat) {
     ...
     //code needed to fill the shield
}

How do I manage to get something like that working in swift?

Cheers, Niklas

Upvotes: 3

Views: 1252

Answers (1)

Lou Franco
Lou Franco

Reputation: 89172

Instead of a PNG do you have the original SVG (or can you get one). If so, I suggest getting PaintCode, which will take this SVG and give you code to draw it with bezier curves -- from there it's very easy to also fill it partially -- you can use the bezier and a rectangle as a mask.

If not, can you modify the png such that it isn't transparent on the outside? If so, you only need to draw the green rectangle underneath and it will show through.

If you need a transparent outside (to overlay on a background), make two copies of the PNG, one with a transparent inside, and one with a transparent outside. Use the first one to make the progress image and then copy the Alpha channel from the second one into the result.

CoreImage and CoreGraphics have the functions you need to do each part -- here is a link for understanding how to get to the pixels (for copying channels):

http://www.raywenderlich.com/69855/image-processing-in-ios-part-1-raw-bitmap-modification

EDIT: Elaboration. You need two images

  1. Image 1 is the shield with a white opaque on the outside and transparent on the inside

  2. Image 2 is the shield with white opaque on the inside and transparent on the outside

Steps:

  1. Draw a green rectangle with the height determined by progress an the bottom set to the inside bottom of the shield onto an image using CoreGraphics

  2. Draw Image 1 on top of that. You now have an image with the shield filled with green progress and white on the outside.

  3. Copy the alpha channel of Image 2 onto the result of Step 2. You now have an image with the progress filled in and a transparent outside.

Upvotes: 2

Related Questions