2011-05-19 99 views

回答

11

好,我實現正弦波入的UIView的drawRect方法如下:

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; 
    } 

在此,x是每個正弦波的寬度,而y是所述框架的高度。這將繪製數量的正弦波以適應整個UIViewFrame。它會產生清脆的正弦波,並且yc是控制手柄。嘗試一下,你可能會喜歡它。

如果寬度ie。 x與框架的寬度相似,則會產生單個正弦波。完整的正弦波的

數=(幀的寬度)/(「x」的每個正弦波的寬度)

+0

它不移動正弦波 – AndrewK 2015-05-07 22:29:46

1

製成的GeneratorOfOne的版本更完整,並迅速版本。這一個也用選定的顏色填充波浪的底部:

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) 
    } 

}