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

前端之家收集整理的这篇文章主要介绍了iOS:CAShapeLayer绘制非直视图像并为其形状设置动画前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我一直在阅读有关CAShapeLayer的文档,但我仍然不太明白.
根据我的理解,Layer始终是扁平的,其大小始终是矩形.

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

我的理解是在这里吗?

我想到的是,例如,一个网球从屏幕边缘反弹(很容易),但我想展示一个不使用图像动画的小动画 – 我希望它显示一点“挤压“喜欢动画,因为它会碰到屏幕的边缘然后反弹.我没有使用网球图像.只是一个黄色的圆圈.

我是否正确使用CAShapeLayer完成此操作?如果是这样,请你提供一个小例子吗?谢谢.

解决方法

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

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];

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

原文链接:https://www.f2er.com/iOS/330407.html

猜你在找的iOS相关文章