iOS自带的动画有时不能满足我们的需要,这时我们需要用到绘图工具
同样地,建一个工程,先引入QuartzCore.framework类库
//新建一个UIView类
#import "GraphicView.h"
#import <QuartzCore/QuartzCore.h>
//UIView的init方法
- (instancetype)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
}
return self;
}
//绘图的方法
- (void)drawRect:(CGRect)rect {
//创建一个绘图工具上下文(画笔)
CGContextRef contextRef = UIGraphicsGetCurrentContext();
//设置画笔的颜色
CGContextSetStrokeColorWithColor(contextRef, [UIColor redColor].CGColor);
//设置填充的颜色
CGContextSetFillColorWithColor(contextRef, [UIColor cyanColor].CGColor);
//上面俩个也可以这么写
//设置画笔的颜色
[[UIColor redColor]setStroke];
//设置填充的颜色
[[UIColor magentaColor]setFill];
//设置绘制的宽度
CGContextSetLineWidth(contextRef, 2);
//让画笔移到某一点,俩点确定一条线,先确定第一点
CGContextMoveToPoint(contextRef, 10, 20);
//添加一条线
CGContextAddLineToPoint(contextRef, 200, 20);
//绘画
CGContextDrawPath(contextRef, kCGPathStroke);
//typedef CF_ENUM (int32_t, CGPathDrawingMode) {
//kCGPathFill,
//kCGPathEOFill,
//kCGPathStroke,
//kCGPathFillStroke,
//kCGPathEOFillStroke
//};
//绘制矩形
CGContextAddRect(contextRef, CGRectMake(10, 40, 100, 100));
//绘制贝塞尔曲线
CGContextAddCurveToPoint(contextRef, 10, 10, 100, 100, 100, 50);
}
绘图与动画的结合
//在.h文件将subView写成属性,并在init方法里面初始化
{
self = [super initWithFrame:frame];
if (self) {
self.backgroundColor = [UIColor whiteColor];
_subView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 10, 10)];
_subView.backgroundColor = [UIColor magentaColor];
[self addSubview:_subView];
}
return self;
}
//
- (void)drawRect:(CGRect)rect {
//绘制路径
CGMutablePathRef path = CGPathCreateMutable();
CGPathAddRect(path, NULL, CGRectMake(10, 40, 100, 100));
//创建动画,这里的@"position"必须写成这个
//self.layer.position
CAKeyframeAnimation * animation = [CAKeyframeAnimation animationWithKeyPath:@"position"];
//动画时长
animation.duration = 3;
//动画重复次数
animation.repeatCount = 100;
//给动画添加路径
animation.path = path;
//subView实现动画
[_subView.layer addAnimation:animation forKey:@"test"];
}
//将GraphicView添加到控制器上,便可以看到效果了