CAKeyframeAnimation实现控件按照手势绘制的路径做动画

本文介绍如何通过自定义UIView来实现触摸绘制路径,并利用Core Animation让视图沿着所绘制的路径做动画。该方法适用于iOS应用开发中需要用户交互绘制及动画效果的场景。

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等方法,不然会被拦截
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值