绘制一个移动的正弦波消除锯齿

时间:2011-05-19 05:05:00

标签: objective-c cocoa-touch ios graphics

我希望以清晰且抗锯齿的方式绘制具有可变频率和可变幅度的移动正弦波。这怎么可能?

2 个答案:

答案 0 :(得分: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是控制手柄。试试你可能会喜欢它。

如果宽度即。 x类似于帧的宽度,然后将产生单个正弦波。

完整正弦波数=(帧宽)/(每个正弦波的'x'宽度)

答案 1 :(得分: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)
    }

}