3

I'm drawing a wave in drawRect method but it appears on the screen all of sudden. I want to animate the process of wave creation e.g wave should be created slowly step by step so that user can see it.
this is the code i am using for drawing my wave

override func drawRect(rect: CGRect) {

    let context = UIGraphicsGetCurrentContext()
    CGContextSetLineWidth(context, 2.0)
    GContextSetStrokeColorWithColor(context, UIColor.redColor().CGColor)
    var startX : CGFloat = 10
    var EndX : CGFloat = 30
    var CpX : CGFloat = 20
    var CpY : CGFloat = 160
    var Y : CGFloat = 200

    for(var i = 0 ; i<5 ; i++ )
    {
        CGContextMoveToPoint(context, startX, Y)
        CGContextAddQuadCurveToPoint(context, CpX, 160, EndX, 200)
        CGContextStrokePath(context)
        startX += 20
        CpX += 20
        EndX += 20

        CGContextMoveToPoint(context, startX, Y)
        CGContextAddQuadCurveToPoint(context, CpX, 240, EndX, 200)
        CGContextStrokePath(context)
        CpX += 20
        startX += 20
        EndX += 20

    }
  }

this is how it looks on screen

Eric Aya
  • 69,473
  • 35
  • 181
  • 253
Umair Afzal
  • 4,947
  • 5
  • 25
  • 50
  • try move all of them in the `[UIView animateWithDuration...]`? – Tj3n Dec 28 '15 at 10:04
  • This isn't exactly what you want but check out CAReplicatorLayer - about 18 mins on the video. https://realm.io/news/altconf-marin-todorov-animations/ – DogCoffee Dec 28 '15 at 10:28

1 Answers1

0

You could put the drawing function in a background task, and add a time delay, but you will need to call the main task when you need to refresh the screen.

As you have it here, this will only show you the wave building up in 5 sections, so you may want to go back to more basic trig functions if you want to see smaller increments

y = yCentre + sin(x * radScalingFactor) * heightScalingFactor

alternatively, you could draw the wave as you have it, and use a background task with time delay loop to gradually remove an opaque view layered over the top

Russell
  • 5,436
  • 2
  • 19
  • 27
  • thanks for your response but i am new in Swift so can you please guide me a little bit more ? i was searching for delay. i want to add a delay of second after drawing of each section of wave. i used `sleep(1)` but with this my whole app goes to sleep – Umair Afzal Dec 29 '15 at 10:27
  • have a look at this answer [link](http://stackoverflow.com/questions/24056205/how-to-use-background-thread-in-swift) any time you want to add a delay, you should use a background thread - you don't want the whole app to freeze! The problem with background when you want to update the display, so you need to put that code in the main thread – Russell Dec 30 '15 at 11:17