2011-05-19 113 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) 
    } 

}