{
//记录是否暂停
BOOL _isMove;
UIButton *Btn;
UIImageView *_earthView;
UIImageView *_moon;
UIImageView *_sunView;
}
@end
@implementation OneViewController
- (void)viewDidLoad {
[super viewDidLoad];
_sunView= [[UIImageView alloc] init];
_sunView.bounds=CGRectMake(0, 0, 60, 60);
_sunView.center=self.view.center;
//默认png可不写
_sunView.image= [UIImage imageNamed:@"fireball.png"];
[self.view addSubview:_sunView];
_earthView= [[UIImageView alloc]init];
_earthView.bounds=CGRectMake(0, 0, 30, 30);
_earthView.frame=CGRectMake(60, 200, 30, 30);
_earthView.image= [UIImage imageNamed:@"26.png"];
[self.view addSubview:_earthView];
_moon= [[UIImageView alloc] init];
_moon.frame=CGRectMake(40, 200, 15, 15);
_moon.image= [UIImage imageNamed:@"a"];
[self.view addSubview:_moon];
//开辟分线程免开启
[NSThread detachNewThreadSelector:@selector(move) toTarget:self withObject:nil];
Btn= [[UIButton alloc] initWithFrame:CGRectMake(50, 50, 40, 40)];
Btn.backgroundColor= [UIColor orangeColor];
Btn.layer.cornerRadius= 15;
[self.view addSubview:Btn];
[Btn setTitle:@"开始" forState:UIControlStateNormal];
[Btn addTarget:self action:@selector(change) forControlEvents:UIControlEventTouchUpInside];
}
//去执行一个动画让地球动起来
-(void)move {
//空for循环保证分线程一直存在
for(; ; ) {
if(_isMove) {
//
//切入主线程刷新UI主线程刷新UI
[selfperform SelectorOnMainThread:@selector(freshUI) withObject:nil waitUntilDone:YES];
[NSThread sleepForTimeInterval:0.3];
}else{
NSLog(@"不转动");
}
}
}
//刷新UI改变地球角度圆周运动
- (void)freshUI {
static int angle;
angle += 30;
//计算视图在角度改变之后的横纵坐标
//先把角度制转换为弧度制
// angle * M_PI / 180
//椭圆120短轴半径160长轴半径
//改变180°会产生不规则运动(100和200半圆运动)
floatx = 160 +120 *cos(angle *M_PI/ 180);
floaty = 240 - 160 *sin(angle *M_PI/ 180);
//刷新视图的center
_earthView.center=CGPointMake(x, y);
_earthView.transform=CGAffineTransformMakeRotation(angle);
//NSLog(@"%@",_earthView);
_moon.center=CGPointMake(x + 40 *cos(2 * angle *M_PI/ 180), y + 40 *sin(2 * angle *M_PI/ 180));
// float x1 = 160 +120 * cos(angle * M_PI / 180);
// float y1 = 240 - 160 * sin(angle * M_PI / 180);
// _moon.center = CGPointMake(x1,y1);
_moon.transform=CGAffineTransformMakeRotation(angle);
_sunView.transform=CGAffineTransformMakeRotation(0.01*angle);
}
- (void)change {
//切换属性值
_isMove= !_isMove;
if(_isMove) {
[Btn setTitle:@"暂停" forState:UIControlStateNormal];
}else{
[Btn setTitle:@"开始" forState:UIControlStateNormal];
}
}