您的位置:首页 > 产品设计 > UI/UE

利用UIGraphics绘制一个会走的时钟

2016-06-02 20:36 483 查看
Controller

@implementation VCRoot

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}

- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
_clockView=[[CustomView alloc]init];
_clockView.frame=CGRectMake(40, 40, 240, 400);
_clockView.backgroundColor=[UIColor cyanColor];
_clockView.alpha=0.5f;
//通知系统让cview视图重新绘制;

[self.view addSubview:_clockView];
}

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
if (_mTimer==nil){
_mTimer=[NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(updateTimer:) userInfo:nil repeats:YES];
}else{
[_mTimer invalidate];
_mTimer=nil;
}
}

-(void)updateTimer:(NSTimer*)mTimer
{
//每秒钟走6度;也就是 1/30*PI
static int i=0;

NSLog(@"%d",i);

float a=0.0f;
a=M_PI*i/30;
NSLog(@"a=%f",a);
NSLog(@"sina=%f",sin(a));
NSLog(@"cosa=%f",cos(a));

//秒针的终点坐标
_clockView.pointEndX1=120+sinf(a)*100;
_clockView.pointEndY1= 200-cosf(a)*100;

//重新加载
[_clockView setNeedsDisplay];

i++;

//每到60要归0;
if (i==60)
{
i=0;
}
}


.h

#import <UIKit/UIKit.h>
#define LEN 20;
#define RADIOUS 100;
#define PI 3.14159;
@interface CustomView : UIView
{
//中心点
float _centerX;
float _centerY;
}
//背景
@property(assign,nonatomic)float pointStartX;
@property(assign,nonatomic)float pointStartY;
@property(assign,nonatomic)float pointEndX;
@property(assign,nonatomic)float pointEndY;

//用于接收传过来的值.秒针的终点坐标
@property(assign,nonatomic)float pointEndX1;
@property(assign,nonatomic)float pointEndY1;

@end


.m

@implementation CustomView

- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// Initialization code
}
return self;
}

// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
// Drawing code
//(120,200) 内径100;
_centerX=120;
_centerY=200;
CGContextRef content=UIGraphicsGetCurrentContext();
float angle=0;
while (angle<=360){
_pointStartX= _centerX+cosf(angle/180*M_PI)*RADIOUS;
_pointStartY=_centerY+sinf(angle/180*M_PI)*RADIOUS;
_pointEndX= _pointStartX+cosf(angle/180*M_PI)*LEN;
_pointEndY=_pointStartY+sinf(angle/180*M_PI)*LEN;

UIColor*colorLine=[UIColor blackColor];
CGContextMoveToPoint(content, _pointStartX, _pointStartY);
[colorLine setStroke];
CGContextAddLineToPoint(content, _pointEndX, _pointEndY);
CGContextStrokePath(content);
angle+=30;
}

//计时器每加一,以下的部分执行一次;
UIColor*colorLine=[UIColor blueColor];

CGContextMoveToPoint(content, _centerX, _centerY);
[colorLine setStroke];
CGContextAddLineToPoint(content, _pointEndX1, _pointEndY1);
CGContextStrokePath(content);

}

运行结果

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: