Drawing a moving sine wave of smoothing

I want to draw a moving sine wave with a variable frequency and variable amplitude in a clear and smooth manner. How is this possible?

+6
source share
2 answers

Well, I applied the sine wave in the drawward UIView method as follows:

float x=75; float yc=50; float w=0; while (w<=rect.frame.size.width) { CGPathMoveToPoint(path, nil, w,y/2); CGPathAddQuadCurveToPoint(path, nil, w+x/4, -yc,w+ x/2, y/2); CGPathMoveToPoint(path, nil, w+x/2,y/2); CGPathAddQuadCurveToPoint(path, nil, w+3*x/4, y+yc, w+x, y/2); CGContextAddPath(context, path); CGContextDrawPath(context, kCGPathStroke); w+=x; } 

Here x is the width of each sine wave, and y is the frame height. This will cause the number of sine waves to match the entire UIViewFrame. This would create a clear sine wave, and yc a control stick. Try it, you may like it.

If the width, i.e. x is similar to the width of the frame, then a sine wave will be created.

Total sine wave number = (frame width) / ('x' width of each sine wave)

+11
source

A more complete and faster version of the GeneratorOfOne version has been made. It also fills the bottom of the wave with the selected color:

 class WaveView: UIView { private var maskPath: UIBezierPath! @IBInspectable var fillColor: UIColor = UIColor.blueColor() @IBInspectable var cycles: CGFloat = 7 override func drawRect(rect: CGRect) { var w: CGFloat = 0 // Starting position let width = rect.width let y: CGFloat = rect.height let yc: CGFloat = rect.height / 2 let x = width/cycles let context = UIGraphicsGetCurrentContext(); CGContextSetFillColorWithColor(context, UIColor.greenColor().CGColor); let path = CGPathCreateMutable(); CGPathMoveToPoint(path, nil, 0, 0) while (w<=rect.width) { CGPathMoveToPoint(path, nil, w,y/2); CGPathAddQuadCurveToPoint(path, nil, w+x/4, -yc, (w+x/2), y/2); CGPathMoveToPoint(path, nil, w+x/2,y/2); CGPathAddQuadCurveToPoint(path, nil, w+3*x/4, y+yc, w+x, y/2); w+=x; } CGPathAddLineToPoint(path, nil, rect.width, rect.height) CGPathAddLineToPoint(path, nil, 0, rect.height) CGPathAddLineToPoint(path, nil, 0, y/2); CGPathCloseSubpath(path) maskPath = UIBezierPath(CGPath: path) maskPath.lineCapStyle = CGLineCap.Square maskPath.lineJoinStyle = CGLineJoin.Miter CGContextAddPath(context, path); CGContextSetFillColorWithColor(context, fillColor.CGColor) CGContextFillPath(context) } } 
+1
source

Source: https://habr.com/ru/post/888499/


All Articles