押すと音が出るだけのドアチャイムみたいなものを作る
(XcodeのiOS6 Simulatorで作っています。)
ポイント
・スピーカーはプチプチを円形に切り取る要領でViewを配置
・音声ファイルをAVAudioPlayerで再生
サンプルコード
#import “ViewController.h”
#import <QuartzCore/QuartzCore.h>
#import <AVFoundation/AVFoundation.h>
@interface ViewController () {
UIView *btn;
AVAudioPlayer *player;
}
@end
@implementation ViewController
– (void)viewDidLoad
{
[super viewDidLoad];
// ドアベルのボディを作る
[self createDoorPhone];
// スピーカーを作る
[self createSpeaker];
// ボタンを作る
[self createButton];
}
– (void)createDoorPhone
{
UIView *body = [[UIView alloc] initWithFrame:CGRectMake(10, 10, 300, 400)];
body.backgroundColor = [UIColor grayColor];
body.layer.cornerRadius = 10.0;
[self.view addSubview:body];
}
– (void)createSpeaker
{
// スピーカーに円形に小さい穴をあける
// プチプチシートみたいに丸を並べて、円の内部だけ切り取るイメージ
int number = 30;
float x,y;
for (int i=0; i<number; i++) {
for (int j=0; j<number; j++) {
x = i*10+15;
y = j*10+15;
if ([self inCircle:CGPointMake(x, y)]) {
UIView *hole = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 6, 6)];
hole.backgroundColor = [UIColor blackColor];
hole.layer.cornerRadius = 3;
hole.center = CGPointMake(x,y);
[self.view addSubview:hole];
}
}}
}
– (void)createButton
{
// UIViewでボタンを作る(影付き)
btn = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 50, 50)];
btn.backgroundColor = [UIColor darkGrayColor];
btn.center = CGPointMake(250, 350);
btn.layer.cornerRadius = 5.0;
btn.layer.shadowOffset = CGSizeMake(2,2);
btn.layer.shadowOpacity = 1.0;
[self.view addSubview:btn];
// ボタンにジェスチャーを追加する
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tap)];
[btn addGestureRecognizer:tap];
}
– (void)tap
{
// 何となく、押した風に動かす
[UIView animateWithDuration:.1 animations:^{
btn.transform = CGAffineTransformMakeScale(0.95, 0.95);
} completion:^(BOOL finished) {
[UIView animateWithDuration:.1 animations:^{
btn.transform = CGAffineTransformMakeScale(1, 1);
}];
}];
// 音を鳴らす
[self callSound];
// 音符を沢山出す
for (int i=0; i<30; i++) {
float th = (M_PI*0.01) * (arc4random() % 200);
UILabel *l = [[UILabel alloc] init];
l.center = CGPointMake(160, 160);
l.font = [UIFont boldSystemFontOfSize:35];
l.text = @”♪”;
l.textColor = [UIColor yellowColor];
l.backgroundColor = [UIColor clearColor];
[l sizeToFit];
l.alpha = 0;
[self.view addSubview:l];
[UIView animateWithDuration:1 delay:0.01*i options:UIViewAnimationCurveLinear animations:^{
l.center = CGPointMake(200 * cos(th) + 160, 200 * sin(th) + 160);
l.alpha = 1.0;
} completion:^(BOOL finished) {
[l removeFromSuperview];
}];
}
}
– (BOOL)inCircle:(CGPoint)p
{
// 円の中かどうか判定
// (x – a)^2 + (y – b)^2 = r^2
if(pow(p.x – 160, 2) + pow(p.y – 160, 2) <= pow(140, 2)) {
return YES;
}
return NO;
}
– (void)callSound
{
// チャイムの音を鳴らす
NSURL *soundURL = [[NSBundle mainBundle] URLForResource:@”chime” withExtension:@”mp3″];
player = [[AVAudioPlayer alloc] initWithContentsOfURL:soundURL error:nil];
[player play];
}
– (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end