iOS:CAShapeLayer绘制非矩形图像并为其形状设置动画

时间:2013-06-08 10:44:00

标签: ios core-animation cashapelayer

我一直在阅读CAShapeLayer上的文档,但我仍然不太明白。 根据我的理解,Layer始终是扁平的,其大小始终是矩形。

另一方面,

CAShapeLayer允许您定义不仅仅是矩形的图层。它可以是圆形,三角形等,只要您与UIBezierPaths一起使用即可。

我的理解是在这里吗?

我想到的是,例如,一个网球从屏幕边缘反弹(很容易),但我想展示一个不使用图像动画的小动画 - 我希望它显示一个像动画一样“挤压”,因为它击中了屏幕的边缘然后反弹。我没有使用网球图像。只是一个黄色的圆圈。

我是否正确CAShapeLayer来完成此任务?如果是这样,请你提供一个小例子吗?感谢。

1 个答案:

答案 0 :(得分:14)

虽然您确实使用路径来定义图层的形状,但它仍然使用用于定义框架/边界的矩形创建。这是一个让你入门的例子:

<强> TennisBall.h:

#import <UIKit/UIKit.h>

@interface TennisBall : UIView

- (void)bounce;

@end

<强> TennisBall.m:

#import <QuartzCore/QuartzCore.h>
#import "TennisBall.h"

@implementation TennisBall

+ (Class)layerClass
{
    return [CAShapeLayer class];
}

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self setupLayer];
    }
    return self;
}

/* Create the tennis ball */
- (void)setupLayer
{
    CAShapeLayer *layer = (CAShapeLayer *)self.layer;
    layer.strokeColor = [[UIColor blackColor] CGColor];
    layer.fillColor = [[UIColor yellowColor] CGColor];
    layer.lineWidth = 1.5;

    layer.path = [self defaultPath];
}

/* Animate the tennis ball "bouncing" off of the side of the screen */
- (void)bounce
{
    CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"path"];
    animation.duration = 0.2;
    animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    animation.fromValue = (__bridge id)[self defaultPath];
    animation.toValue = (__bridge id)[self compressedPath];
    animation.autoreverses = YES;
    [self.layer addAnimation:animation forKey:@"animatePath"];
}

/* A path representing the tennis ball in the default state */
- (CGPathRef)defaultPath
{
    return [[UIBezierPath bezierPathWithOvalInRect:self.frame] CGPath];
}

/* A path representing the tennis ball is the compressed state (during the bounce) */
- (CGPathRef)compressedPath
{
    CGRect newFrame = CGRectMake(self.frame.origin.x, self.frame.origin.y, self.frame.size.width * 0.85, self.frame.size.height);
    return [[UIBezierPath bezierPathWithOvalInRect:newFrame] CGPath];
}

@end

现在,当你想要使用它时:

TennisBall *ball = [[TennisBall alloc] initWithFrame:CGRectMake(10, 10, 100, 100)];
[self.view addSubview:ball];

[ball bounce];

请注意,这需要进行扩展,以便您可以从不同角度“反弹”等,但它应该让您指向正确的方向!