如何绘制波形?

时间:2015-10-14 21:07:41

标签: ios objective-c audio waveform

我使用Superpowered SDK播放声音。 它有一个函数返回名为peakWaveForm的unsigned char **。 我写了一个自定义uiview并试图绘制这些值,我的观点并不好看。我的问题是,绘制波形的值应该是多少? 什么样的变量。数组?。波形的正常大小应该是多少? SDK返回一个unsigned char **我该怎么办?

- (void)drawRect:(CGRect)updateRect
{
    unsigned i, maxIndex;

    maxIndex = floor(CGRectGetMaxX(updateRect));
    i = floor(CGRectGetMinX(updateRect));
    float firstPoint = (float)mPeakWaveForm[0][i];

    UIBezierPath *path = [UIBezierPath bezierPath];
    path.lineWidth = 2;
   [[UIColor blackColor] setFill];
   [path moveToPoint:CGPointMake(i,firstPoint)];

   for(i; i <= maxIndex; i++)
   {
       float nextPoint = (float)mPeakWaveForm[0][i];
      [path addLineToPoint:CGPointMake(i, nextPoint)];
   }
   [path fill];
}

1 个答案:

答案 0 :(得分:0)

我和你处于同样的境地,并以这种方式解决了。 首先,您只获得一维数据阵列中的波形,我们希望它在两个轴上都有2d。 所以我所做的是创建一个数组点,而不是直接绘制路径,然后绘制路径一次,另一次镜像围绕x轴,如下所示:

    var points = Array<CGPoint>()
    for(i; i <= maxIndex; i++)
    {
       float nextPoint = (float)mPeakWaveForm[0][i];
       points.append(CGPoint(x: CGFloat(i), y: CGFloat(nextPoint)))
    }
    //Move to the center of the view
    var xf = CGAffineTransformIdentity;
    xf = CGAffineTransformTranslate(xf, 0, halfHeight)
    //Scale it as needed (you can avoid it)
    xf = CGAffineTransformScale(xf, xscale, yscale)

    let path = CGPathCreateMutable()
    //Draw the lines
    CGPathAddLines(path, &xf, points, points.count)

    //Mirror the drawing and draw them again
    xf = CGAffineTransformScale(xf, 1.0, -1.0);
    CGPathAddLines(path, &xf, points, points.count);

    CGPathCloseSubpath(path)
    //Draw the path
    let ctx = UIGraphicsGetCurrentContext();
    CGContextAddPath(ctx, path);
    CGContextSetStrokeColorWithColor(ctx,UIColor.whiteColor().CGColor);
    CGContextFillPath(ctx);

很抱歉代码在swift中,但功能与Objective-C中的相同