这个效果类似于这个哦:
效果如下:
源码:
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 <= 0) { _progress = 0; } else if (progress >= 1) { _progress = 1; } else { _progress = progress; } [UIView animateWithDuration:(_timeInterval > 0 ? _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(100, 100, 4, 20)]; _musicViewLine1.backgroundColor = [UIColor redColor]; _musicViewLine1.timeInterval = 0.5f; [self.view addSubview:_musicViewLine1]; // 线条2 _musicViewLine2 = [[MusicView alloc] initWithFrame:CGRectMake(108, 100, 4, 20)]; _musicViewLine2.backgroundColor = [UIColor redColor]; _musicViewLine2.timeInterval = 0.5f; [self.view addSubview:_musicViewLine2]; // 线条3 _musicViewLine3 = [[MusicView alloc] initWithFrame:CGRectMake(116, 100, 4, 20)]; _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()%100/100.f; _musicViewLine2.progress = arc4random()%100/100.f; _musicViewLine3.progress = arc4random()%100/100.f; } @end
以下是核心代码:
绘制播放音乐时的音波图形的View,布布扣,bubuko.com
时间: 2024-10-16 00:01:09