绘制一个音频频谱显示View

Untitled.gif

废话少说,直接看代码

#import <UIKit/UIKit.h>

#define CalcPT(x) (x)

#define kVolumeCount      (5)
#define kVolumeWidth      CalcPT(8)
#define kVolumeMargin     CalcPT(2.5)
#define kVolumeViewHeight CalcPT(24)
#define kVolumeViewWidth  (kVolumeCount*kVolumeWidth+(kVolumeCount-1)*kVolumeMargin)

@interface VolumeView : UIView
- (void)setMainVolume: (CGFloat)volume maxDurtion: (CGFloat)time;
- (BOOL)setVolume: (CGFloat)volume index: (NSUInteger)index maxDurtion: (CGFloat)time;
@end

#import "VolumeView.h"

@implementation VolumeView
{
    NSMutableArray <UIImageView *>*_imageViews;
}

- (instancetype)init
{
    if (self = [super init])
    {
        _imageViews = NewMutableArray();
        self.clipsToBounds = YES;
        self.backgroundColor = ClearColor;
        self.frame = CGRectMake(0, 0, kVolumeViewWidth, kVolumeViewHeight);
        
        CGFloat x = 0;
        
        for (NSUInteger a = 0; a < kVolumeCount; ++a)
        {
            UIImageView *iv = NewClass(UIImageView);
            iv.frame = CGRectMake(x, 0, kVolumeWidth, kVolumeViewHeight);
            iv.contentMode = UIViewContentModeScaleAspectFit;
            iv.image = GetImageWithName(@"pic-music");
            iv.backgroundColor = ClearColor;
            [_imageViews addObject:iv];
            [self addSubview:iv];
            
            x += kVolumeWidth + kVolumeMargin;
        }
    }
    
    return self;
}

- (BOOL)setVolume: (CGFloat)volume index: (NSUInteger)index maxDurtion: (CGFloat)time
{
    const UIImageView *iv = _imageViews[index];
    if (iv.tag++) return NO;
    
    const CGFloat h = self.height;
    const CGFloat y = h * (1.0f - volume);
    const CGFloat d = (iv.y > y ? iv.y - y : y - iv.y) / h;
    const CGFloat t = d * time;
    
    runBlockWithMain(^{
        [UIView animateWithDuration:t animations:^{
            iv.y = y;
        } completion:^(BOOL finished) {
            iv.tag = 0;
        }];
    });
    
    return YES;
}

- (void)setMainVolume: (CGFloat)volume maxDurtion: (CGFloat)time
{
    const NSUInteger count = _imageViews.count;
    
    for (NSUInteger a = 0; a < count; ++a)
    {
        const CGFloat x = 1 - (arc4random()%51)/100.0f;
        const CGFloat v = x * volume;
        [self setVolume:v index:a maxDurtion:time];
    }
}
@end

推荐阅读更多精彩内容