1.要绘制路径,需要自定义View
DrawView
//
// DrawView.m
#import "DrawView.h"
@interface DrawView()
@property(nonatomic,strong)UIBezierPath *path;
@end
@implementation DrawView
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [touches anyObject];
CGPoint currentP = [touch locationInView:self];
// 创建路径
UIBezierPath *path = [UIBezierPath bezierPath];
_path = path;
// 设置路径起点
[path moveToPoint:currentP];
}
- (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [touches anyObject];
CGPoint currentP = [touch locationInView:self];
// 添加点到当前路径
[_path addLineToPoint:currentP];
// 重绘
[self setNeedsDisplay];
}
/**
* 手指立刻,让控件按照我们绘制的路径做动画
*/
- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
// // 创建动画
CAKeyframeAnimation *anim = [CAKeyframeAnimation animation];
anim.keyPath = @"position";
anim.path = _path.CGPath;
anim.repeatCount = MAXFLOAT;
anim.duration = 1;
[[[self.subviews firstObject] layer] addAnimation:anim forKey:nil];
}
- (void)drawRect:(CGRect)rect
{
[_path stroke];
}
@end
注意,控制器里不要实现touch等方法,不然会被拦截
本文介绍如何通过自定义UIView来实现触摸绘制路径,并利用Core Animation让视图沿着所绘制的路径做动画。该方法适用于iOS应用开发中需要用户交互绘制及动画效果的场景。
1006

被折叠的 条评论
为什么被折叠?



