您的位置:首页 > 其它

定时器实现的地球围绕太阳旋转

2015-01-03 22:48 246 查看
一个地球围绕太阳旋转

#import "HUAppDelegate.h"

#define CENTER_X 160
#define CENTER_Y 240
#define RADIUS 120

@implementation HUAppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
self.window.backgroundColor = [UIColor blackColor];
[self.window makeKeyAndVisible];

UIImageView * sun = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"fireball"]];
sun.center = CGPointMake(CENTER_X, CENTER_Y);
sun.bounds = CGRectMake(0, 0, 70, 70);
[self.window addSubview:sun];

_earthArray = [[NSMutableArray alloc] init];
for (int i = 0; i < 12; i ++)  //有 12 个地球同时旋转
{
UIImageView *earth = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"earth"]];
int angle = 30 * i;
float huDu = angle * M_PI / 180;
earth.center = CGPointMake(CENTER_X + RADIUS * cos(huDu), CENTER_Y + 1.5 * RADIUS * sin(huDu));
earth.bounds = CGRectMake(0, 0, 35, 35);
[self.window addSubview:earth];
[_earthArray addObject:earth];
}

[NSTimer scheduledTimerWithTimeInterval:0.01 target:self selector:@selector(rotate) userInfo:nil repeats:YES];

return YES;
}

- (void)rotate
{
static int count = 0;
count ++;
for (int i = 0; i < 12; i ++)
{
UIImageView *earth = [_earthArray objectAtIndex:i]; //获取当前地球的起始角度,一遍获取其起始角度
int angle = 30 * i + count;  //获取当前地球的起始角度,然后开始运动
float huDu = angle * M_PI / 180;
earth.center = CGPointMake(CENTER_X + RADIUS * cos(huDu), CENTER_Y + 1.5 * RADIUS * sin(huDu));
}

}

@end


View Code
也可以自定义一个继承自 UIImageView 的类,添加一个记载其当前角度的属性

@property int angle;

然后在 rotate 方法里就不需要静态变量来改变“地球”当前的角度

- (void)rotate
{
for (int i = 0 ; i < _earthArray.count; i ++)
{
EarthImageView *earth = [_earthArray objectAtIndex:i];
earth.angle += 1;
float huDu = earth.angle * M_PI / 180;
earth.center = CGPointMake(CENTER_X + RADIUS * cos(huDu), CENTER_Y + 1.5 * RADIUS * sin(huDu));
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: