此博客记录学习A GUIDE TO IOS ANIMATION 2.0这本书的过程中的一些心得,也是个人一些经验
首先,第一章玩转贝塞尔曲线.之前只接触到的画图方法是先创建一个类,继承自UIView,在这个类中重写 -(void)drawRect:(CGRect)rect方法,可实现画图.其代码实现分三步:1.获得上下文 2.拼接路径(绘制图形) 3.渲染图形
在本章中将学习中将学习一种新的画图方法,原理类似:创建一个继承CALayer的类,然后在这个类中重写- (void)drawInContext:(CGContextRef)ctx方法来实现画图,下面是代码实现
首先创建一个创建一个继承自CALayer的类
#import "LMYAnimationLayer.h"
@implementation LMYAnimationLayer
- (void)drawInContext:(CGContextRef)ctx {
//画一个圆,可用两种方法,下面两种方法实现的效果相同
//用画椭圆的方式,要注意的是第二个参数的rect的x和y不是圆心的位置,
//而是约束这个圆的外接矩形的frame种的值
// CGContextAddEllipseInRect(ctx, CGRectMake(0, 0, 100, 100));
//直接用画圆的方法
CGContextAddArc(ctx, 160, 160, 50, 0, M_PI * 2, 1);
//设置颜色
CGContextSetRGBFillColor(ctx, 0, 0, 1, 1);
//渲染
CGContextFillPath(ctx);
}
@end
然后创建一个自定义的View,重写initWithFrame:方法,添加上面创建的layer,最终在控制其中添加这个自定义的view,即可显示,代码如下
- (instancetype)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) {
self.aniLayer = [LMYAnimationLayer layer];
//在此处之后就可以调用setNeedsDisplay方法
self.aniLayer.frame = self.bounds;
self.aniLayer.contentsScale = [UIScreen mainScreen].scale;
self.aniLayer.backgroundColor = [UIColor whiteColor].CGColor;
[self.layer addSublayer:self.aniLayer];
[self.aniLayer setNeedsDisplay];
}
return self;
}
@end
最后在控制器中添加
#import "LMYAnimationView.h"
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
LMYAnimationView *testView = [[LMYAnimationView alloc] initWithFrame:CGRectMake(self.view.frame.size.width / 2 - 320 / 2, self.view.frame.size.height / 2 - 320 / 2, 320, 320)];
testView.backgroundColor = [UIColor orangeColor];
[self.view addSubview:testView];
}
@end
到此,准备工作已经大体完成.