需要导入 QuartzCore.framework
代码
#import "DrawView.h"
#import <QuartzCore/QuartzCore.h>
@implementation DrawView
- (instancetype)init
{
self = [super init];
if (self) {
subview = [[UIView alloc] init];
subview.frame = CGRectMake(0, 0, 10, 10);
subview.backgroundColor = [UIColor redColor];
[self addSubview:subview];
}
return self;
}
- (void)drawRect:(CGRect)rect {
// 绘图上下文(画布)
CGContextRef ctx = UIGraphicsGetCurrentContext();
// 画笔颜色
CGContextSetStrokeColorWithColor(ctx, [UIColor redColor].CGColor);
// 设置填充颜色(矩形、圆等)
//CGContextSetFillColorWithColor(ctx, [UIColor greenColor].CGColor);
// 功能同上
//[[UIColor purpleColor] setStroke]; // 线
//[[UIColor greenColor]setFill]; // 填充颜色
// 线条宽度
CGContextSetLineWidth(ctx, 2.0);
// 画笔移动到某点(开始的位置)
CGContextMoveToPoint(ctx, 0, 0);
// 画线
//CGContextAddLineToPoint(ctx, self.frame.size.width, self.frame.size.height);
// 画多条线
//CGContextAddLines(<#CGContextRef c#>, <#const CGPoint *points#>, <#size_t count#>)
// 画矩形
CGContextAddRect(ctx, CGRectMake(10, 10, 80, 80));
// 贝塞尔曲线
//CGContextAddCurveToPoint(ctx, 20, 80, 200, 150, 50, 100);
/*
kCGPathFill, // 填充
kCGPathEOFill,
kCGPathStroke, // 线
kCGPathFillStroke, // 线和填充
kCGPathEOFillStroke
*/
CGContextDrawPath(ctx, kCGPathStroke); // 开始画
// 绘制路径
CGMutablePathRef path = CGPathCreateMutable();
//CGPathAddCurveToPoint(<#CGMutablePathRef path#>, <#const CGAffineTransform *m#>, <#CGFloat cp1x#>, <#CGFloat cp1y#>, <#CGFloat cp2x#>, <#CGFloat cp2y#>, <#CGFloat x#>, <#CGFloat y#>)
CGPathAddRect(path, NULL, CGRectMake(10, 10, 80, 80));
CAKeyframeAnimation *animation = [CAKeyframeAnimation animationWithKeyPath:@"position"];
animation.duration = 3.0;
animation.timingFunction = [CAMediaTimingFunction functionWithName:@"easeInEaseOut"];
animation.repeatCount = 20.0;
animation.path = path;
[subview.layer addAnimation:animation forKey:@"suibianxie"];
// UIImage *image = [UIImage imageNamed:@"abc"];
// [image drawInRect:<#(CGRect)#>]
}