Objective-Cのタイマーを使用してラベルをアニメーションさせるサンプルを以下に作成しました。
サンプルでは、一定間隔でラベルの座標を更新する事でアニメーションを実装しています。
サンプルダウンロード
ソースコード
ViewController.h
1
2
3
4
5
6
7
8
9
10
11
| #import <UIKit/UIKit.h>
@interface ViewController : UIViewController
@property (nonatomic) int labelWidth;
@property (nonatomic) int labelHeight;
@property (nonatomic) int animationSpeedX;
@property (nonatomic) int animationSpeedY;
@property (strong, nonatomic) UILabel* myLabel;
@end
|
ViewController.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
| #import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
//アニメーションさせるラベル初期化
[self initLabel];
//アニメーション設定
[self setAnimationSettings];
//タイマー定義
[self setTimer];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
//ラベル初期化
- (void)initLabel
{
//ラベルを生成
self.labelWidth = 128;
self.labelHeight = 32;
self.myLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, self.labelWidth, self.labelHeight)];
self.myLabel.text = @"Animation";
[self.view addSubview:self.myLabel];
}
//アニメーション設定
- (void)setAnimationSettings
{
//ラベルのアニメーションスピード
self.animationSpeedX = 2;
self.animationSpeedY = 1;
}
//タイマー定義
- (void)setTimer
{
//0.01秒毎に moveLabelセレクタを呼ぶ
[NSTimer
scheduledTimerWithTimeInterval:0.01
target:self
selector:@selector(moveLabel:)
userInfo:nil
repeats:YES];
}
//ラベルをアニメーションさせるセレクタ
- (void)moveLabel:(NSTimer *)timer {
float posX = self.myLabel.center.x;
float posY = self.myLabel.center.y;
//ラベルを移動させる
posX += self.animationSpeedX;
posY += self.animationSpeedY;
//端までアニメーションしたか判定
if ([self isLimitLabelX:posX]) posX = 0;
if ([self isLimitLabelY:posY]) posY = 0;
//座標反映
self.myLabel.center = CGPointMake(posX, posY);
}
//横方向の端まで行ったか判定
- (BOOL)isLimitLabelX:(int)posX
{
return (self.view.frame.size.width + self.labelWidth < posX);
}
//縦方向の端まで行ったか判定
- (BOOL)isLimitLabelY:(int)posY
{
return (self.view.frame.size.height + self.labelHeight < posY);
}
@end
|
関連記事
お薦めの参考書
Cocos2d-xでゲームを開発したいという方に必携の1冊です。実際にゲームを作りながら学習して行く内容で、とても身に付き易い構成になっています。プログラミング経験はあるけれどゲーム開発は未経験という方にお薦めの内容となっております。