Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift Progress Indicator Image Mask

To start, this project has been built using Swift.

I want to create a custom progress indicator that "fills up" as the script runs. The script will call a JSON feed that is pulled from the remote server.

To better visualize what I'm after, I made this:

enter image description here

My guess would be to have two PNG images; one white and one red, and then simply do some masking based on the progress amount.

Any thoughts on this?

like image 336
matcartmill Avatar asked Jan 11 '15 00:01

matcartmill


1 Answers

Masking is probably overkill for this. Just redraw the image each time. When you do, you draw the red rectangle to fill the lower half of the drawing, to whatever height you want it; then you draw the droplet image (a PNG), which has transparency in the middle so the red rectangle shows through. So, one PNG is enough because the red rectangle can be drawn "live" each time you redraw.

I liked your drawing so much that I wanted to bring it to life, so here's my working code (my PNG is called tear.png and iv is a UIImageView in my interface; percent should be a CGFloat between 0 and 1):

func redraw(percent:CGFloat) {
    let tear : UIImage! = UIImage(named:"tear")!
    if tear == nil {return}
    let sz = tear.size
    let top = sz.height*(1-percent)
    UIGraphicsBeginImageContextWithOptions(sz, false, 0)
    let con = UIGraphicsGetCurrentContext()
    UIColor.redColor().setFill()
    CGContextFillRect(con, CGRectMake(0,top,sz.width,sz.height))
    tear.drawAtPoint(CGPointMake(0,0))
    self.iv.image = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
}

I also hooked up a UISlider whose action method converts its value to a CGFloat and calls that method, so that moving the slider back and forth moves the red fill up and down in the teardrop. I could play with this for hours!

enter image description here

like image 85
matt Avatar answered Oct 21 '22 12:10

matt