绘制播放音乐时的音波图形的View

时间:2023-03-10 06:34:14
绘制播放音乐时的音波图形的View

绘制播放音乐时的音波图形的View

绘制播放音乐时的音波图形的View

这个效果类似于这个哦:

绘制播放音乐时的音波图形的View

效果如下:

绘制播放音乐时的音波图形的View

源码:

MusicView.h 与 MusicView.m

//
// MusicView.h
// Music
//
// Copyright (c) 2014年 Y.X. All rights reserved.
// #import <UIKit/UIKit.h> @interface MusicView : UIView @property (nonatomic, assign) CGFloat progress; // 进程百分比,取值为[0,1]
@property (nonatomic, assign) CGFloat timeInterval; // 时间间隔 @end
//
// MusicView.m
// Music
//
// Copyright (c) 2014年 Y.X. All rights reserved.
// #import "MusicView.h" @interface MusicView () @property (nonatomic, assign) CGRect baseRect; // 备份原始的frame值 @end @implementation MusicView - (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
_baseRect = frame;
}
return self;
} @synthesize progress = _progress;
- (void)setProgress:(CGFloat)progress
{
if (progress <= ) {
_progress = ;
} else if (progress >= ) {
_progress = ;
} else {
_progress = progress;
} [UIView animateWithDuration:(_timeInterval > ? _timeInterval : 0.99) animations:^{
CGRect rect = _baseRect;
rect.size.height *= _progress;
self.frame = rect;
}];
}
- (CGFloat)progress
{
return _progress;
} @end

使用时的情形:

//
// RootViewController.m
// Music
//
// Copyright (c) 2014年 Y.X. All rights reserved.
// #import "RootViewController.h"
#import "MusicView.h" @interface RootViewController () @property (nonatomic, strong) NSTimer *timer;
@property (nonatomic, strong) MusicView *musicViewLine1;
@property (nonatomic, strong) MusicView *musicViewLine2;
@property (nonatomic, strong) MusicView *musicViewLine3; @end @implementation RootViewController - (void)viewDidLoad
{
[super viewDidLoad]; // 线条1
_musicViewLine1 = [[MusicView alloc] initWithFrame:CGRectMake(, , , )];
_musicViewLine1.backgroundColor = [UIColor redColor];
_musicViewLine1.timeInterval = 0.5f;
[self.view addSubview:_musicViewLine1]; // 线条2
_musicViewLine2 = [[MusicView alloc] initWithFrame:CGRectMake(, , , )];
_musicViewLine2.backgroundColor = [UIColor redColor];
_musicViewLine2.timeInterval = 0.5f;
[self.view addSubview:_musicViewLine2]; // 线条3
_musicViewLine3 = [[MusicView alloc] initWithFrame:CGRectMake(, , , )];
_musicViewLine3.backgroundColor = [UIColor redColor];
_musicViewLine3.timeInterval = 0.5f;
[self.view addSubview:_musicViewLine3]; _timer = [NSTimer scheduledTimerWithTimeInterval:0.5f
target:self
selector:@selector(timerEvent)
userInfo:nil
repeats:YES];
} - (void)timerEvent
{
_musicViewLine1.progress = arc4random()%/.f;
_musicViewLine2.progress = arc4random()%/.f;
_musicViewLine3.progress = arc4random()%/.f;
} @end

以下是核心代码:

绘制播放音乐时的音波图形的View