aah*_*ali 4 core-animation objective-c caanimation ios
我使用CAShapeLayer和masking创建了一个圆形动画.这是我的代码:
- (void) maskAnimation{
animationCompletionBlock theBlock;
imageView.hidden = FALSE;//Show the image view
CAShapeLayer *maskLayer = [CAShapeLayer layer];
CGFloat maskHeight = imageView.layer.bounds.size.height;
CGFloat maskWidth = imageView.layer.bounds.size.width;
CGPoint centerPoint;
centerPoint = CGPointMake( maskWidth/2, maskHeight/2);
//Make the radius of our arc large enough to reach into the corners of the image view.
CGFloat radius = sqrtf(maskWidth * maskWidth + maskHeight * maskHeight)/2;
//Don't fill the path, but stroke it in black.
maskLayer.fillColor = [[UIColor clearColor] CGColor];
maskLayer.strokeColor = [[UIColor blackColor] CGColor];
maskLayer.lineWidth = 60;
CGMutablePathRef arcPath = CGPathCreateMutable();
//Move to the starting point of the arc so there is no initial line connecting to the arc
CGPathMoveToPoint(arcPath, nil, centerPoint.x, centerPoint.y-radius/2);
//Create an arc at 1/2 our circle radius, with a line thickess of the full circle radius
CGPathAddArc(arcPath,
nil,
centerPoint.x,
centerPoint.y,
radius/2,
3*M_PI/2,
-M_PI/2,
NO);
maskLayer.path = arcPath;//[aPath CGPath];//arcPath;
//Start with an empty mask path (draw 0% of the arc)
maskLayer.strokeEnd = 0.0;
CFRelease(arcPath);
//Install the mask layer into out image view's layer.
imageView.layer.mask = maskLayer;
//Set our mask layer's frame to the parent layer's bounds.
imageView.layer.mask.frame = imageView.layer.bounds;
//Create an animation that increases the stroke length to 1, then reverses it back to zero.
CABasicAnimation *swipe = [CABasicAnimation animationWithKeyPath:@"strokeEnd"];
swipe.duration = 5;
swipe.delegate = self;
[swipe setValue: theBlock forKey: kAnimationCompletionBlock];
swipe.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear];
swipe.fillMode = kCAFillModeForwards;
swipe.removedOnCompletion = NO;
swipe.autoreverses = YES;
swipe.toValue = [NSNumber numberWithFloat: 1.0];
[maskLayer addAnimation: swipe forKey: @"strokeEnd"];
}
Run Code Online (Sandbox Code Playgroud)
这是我的背景图片:

这是我运行动画时的样子:

但是我想要的是,箭头缺少如何添加这个?

rob*_*off 17
由于我的另一个答案(动画两级掩码)有一些图形故障,我决定尝试在每一帧动画上重绘路径.所以首先让我们写一个CALayer类似的子类CAShapeLayer,但只是绘制一个箭头.我最初尝试将其作为子类CAShapeLayer,但我无法让Core Animation正确地为其设置动画.
无论如何,这是我们要实现的接口:
@interface ArrowLayer : CALayer
@property (nonatomic) CGFloat thickness;
@property (nonatomic) CGFloat startRadians;
@property (nonatomic) CGFloat lengthRadians;
@property (nonatomic) CGFloat headLengthRadians;
@property (nonatomic, strong) UIColor *fillColor;
@property (nonatomic, strong) UIColor *strokeColor;
@property (nonatomic) CGFloat lineWidth;
@property (nonatomic) CGLineJoin lineJoin;
@end
Run Code Online (Sandbox Code Playgroud)
该startRadians属性是尾部末端的位置(以弧度表示).的lengthRadians是从尾到箭头的尖端的端部的长度(单位为弧度).的headLengthRadians是箭头的长度(单位为弧度).
我们还重现了一些属性CAShapeLayer.我们不需要该lineCap属性,因为我们总是绘制一个封闭的路径.
那么,我们如何实现这个疯狂的事情呢?实际上,CALayer将负责存储您要在子类上定义的任何旧属性.首先,我们告诉编译器不要担心合成属性:
@implementation ArrowLayer
@dynamic thickness;
@dynamic startRadians;
@dynamic lengthRadians;
@dynamic headLengthRadians;
@dynamic fillColor;
@dynamic strokeColor;
@dynamic lineWidth;
@dynamic lineJoin;
Run Code Online (Sandbox Code Playgroud)
但是我们需要告诉Core Animation,如果这些属性发生任何变化,我们需要重新绘制图层.为此,我们需要一个属性名称列表.我们将使用Objective-C运行时获取列表,因此我们不必重新键入属性名称.我们需要#import <objc/runtime.h>在文件的顶部,然后我们可以得到这样的列表:
+ (NSSet *)customPropertyKeys {
static NSMutableSet *set;
static dispatch_once_t once;
dispatch_once(&once, ^{
unsigned int count;
objc_property_t *properties = class_copyPropertyList(self, &count);
set = [[NSMutableSet alloc] initWithCapacity:count];
for (int i = 0; i < count; ++i) {
[set addObject:@(property_getName(properties[i]))];
}
free(properties);
});
return set;
}
Run Code Online (Sandbox Code Playgroud)
现在我们可以编写Core Animation用来找出需要重绘的属性的方法:
+ (BOOL)needsDisplayForKey:(NSString *)key {
return [[self customPropertyKeys] containsObject:key] || [super needsDisplayForKey:key];
}
Run Code Online (Sandbox Code Playgroud)
事实证明,Core Animation将在每一帧动画中制作我们图层的副本.我们需要确保在Core Animation制作副本时复制所有这些属性:
- (id)initWithLayer:(id)layer {
if (self = [super initWithLayer:layer]) {
for (NSString *key in [self.class customPropertyKeys]) {
[self setValue:[layer valueForKey:key] forKey:key];
}
}
return self;
}
Run Code Online (Sandbox Code Playgroud)
我们还需要告诉Core Animation,如果图层的边界发生变化,我们需要重绘:
- (BOOL)needsDisplayOnBoundsChange {
return YES;
}
Run Code Online (Sandbox Code Playgroud)
最后,我们可以了解绘制箭头的细节.首先,我们将图形上下文的原点更改为图层边界的中心.然后我们将构建概述箭头的路径(现在以原点为中心).最后,我们将适当地填充和/或描边路径.
- (void)drawInContext:(CGContextRef)gc {
[self moveOriginToCenterInContext:gc];
[self addArrowToPathInContext:gc];
[self drawPathOfContext:gc];
}
Run Code Online (Sandbox Code Playgroud)
将原点移动到我们边界的中心是微不足道的:
- (void)moveOriginToCenterInContext:(CGContextRef)gc {
CGRect bounds = self.bounds;
CGContextTranslateCTM(gc, CGRectGetMidX(bounds), CGRectGetMidY(bounds));
}
Run Code Online (Sandbox Code Playgroud)
构建箭头路径并非易事.首先,我们需要获得尾部开始的径向位置,尾部和箭头开始的径向位置,以及箭头尖端的径向位置.我们将使用辅助方法来计算这三个径向位置:
- (void)addArrowToPathInContext:(CGContextRef)gc {
CGFloat startRadians;
CGFloat headRadians;
CGFloat tipRadians;
[self getStartRadians:&startRadians headRadians:&headRadians tipRadians:&tipRadians];
Run Code Online (Sandbox Code Playgroud)
然后我们需要弄清楚箭头内外圆弧的半径和尖端的半径:
CGFloat thickness = self.thickness;
CGFloat outerRadius = self.bounds.size.width / 2;
CGFloat tipRadius = outerRadius - thickness / 2;
CGFloat innerRadius = outerRadius - thickness;
Run Code Online (Sandbox Code Playgroud)
我们还需要知道我们是以顺时针还是逆时针方向绘制外弧:
BOOL outerArcIsClockwise = tipRadians > startRadians;
Run Code Online (Sandbox Code Playgroud)
内弧将沿相反方向绘制.
最后,我们可以构建路径.我们移动到箭头的尖端,然后添加两个弧.该CGPathAddArc调用会自动从路径的当前点添加一条直线到弧的起点,因此我们不需要自己添加任何直线:
CGContextMoveToPoint(gc, tipRadius * cosf(tipRadians), tipRadius * sinf(tipRadians));
CGContextAddArc(gc, 0, 0, outerRadius, headRadians, startRadians, outerArcIsClockwise);
CGContextAddArc(gc, 0, 0, innerRadius, startRadians, headRadians, !outerArcIsClockwise);
CGContextClosePath(gc);
}
Run Code Online (Sandbox Code Playgroud)
现在让我们弄清楚如何计算这三个径向位置.这将是微不足道的,除非我们希望在头部长度大于总长度时通过将头部长度剪切到总长度来优雅.我们还想让总长度为负,以向相反方向绘制箭头.我们首先选择起始位置,总长度和头部长度.我们将使用一个帮助剪裁头部长度不超过总长度:
- (void)getStartRadians:(CGFloat *)startRadiansOut headRadians:(CGFloat *)headRadiansOut tipRadians:(CGFloat *)tipRadiansOut {
*startRadiansOut = self.startRadians;
CGFloat lengthRadians = self.lengthRadians;
CGFloat headLengthRadians = [self clippedHeadLengthRadians];
Run Code Online (Sandbox Code Playgroud)
接下来,我们计算尾部与箭头相交的径向位置.我们小心翼翼地这样做,这样如果我们剪掉头部长度,我们就会准确计算起始位置.这很重要,因此当我们CGPathAddArc使用两个位置调用时,由于浮点舍入,它不会添加意外的弧.
// Compute headRadians carefully so it is exactly equal to startRadians if the head length was clipped.
*headRadiansOut = *startRadiansOut + (lengthRadians - headLengthRadians);
Run Code Online (Sandbox Code Playgroud)
最后我们计算出箭头尖端的径向位置:
*tipRadiansOut = *startRadiansOut + lengthRadians;
}
Run Code Online (Sandbox Code Playgroud)
我们需要编写剪辑头长的帮助器.它还需要确保头部长度与总长度具有相同的符号,因此上面的计算正常工作:
- (CGFloat)clippedHeadLengthRadians {
CGFloat lengthRadians = self.lengthRadians;
CGFloat headLengthRadians = copysignf(self.headLengthRadians, lengthRadians);
if (fabsf(headLengthRadians) > fabsf(lengthRadians)) {
headLengthRadians = lengthRadians;
}
return headLengthRadians;
}
Run Code Online (Sandbox Code Playgroud)
要在图形上下文中绘制路径,我们需要根据属性设置上下文的填充和描边参数,然后调用CGContextDrawPath:
- (void)drawPathOfContext:(CGContextRef)gc {
CGPathDrawingMode mode = 0;
[self setFillPropertiesOfContext:gc andUpdateMode:&mode];
[self setStrokePropertiesOfContext:gc andUpdateMode:&mode];
CGContextDrawPath(gc, mode);
}
Run Code Online (Sandbox Code Playgroud)
如果给出填充颜色,我们填写路径:
- (void)setFillPropertiesOfContext:(CGContextRef)gc andUpdateMode:(CGPathDrawingMode *)modeInOut {
UIColor *fillColor = self.fillColor;
if (fillColor) {
*modeInOut |= kCGPathFill;
CGContextSetFillColorWithColor(gc, fillColor.CGColor);
}
}
Run Code Online (Sandbox Code Playgroud)
如果给出笔触颜色和线宽,我们会描边路径:
- (void)setStrokePropertiesOfContext:(CGContextRef)gc andUpdateMode:(CGPathDrawingMode *)modeInOut {
UIColor *strokeColor = self.strokeColor;
CGFloat lineWidth = self.lineWidth;
if (strokeColor && lineWidth > 0) {
*modeInOut |= kCGPathStroke;
CGContextSetStrokeColorWithColor(gc, strokeColor.CGColor);
CGContextSetLineWidth(gc, lineWidth);
CGContextSetLineJoin(gc, self.lineJoin);
}
}
Run Code Online (Sandbox Code Playgroud)
结束!
@end
Run Code Online (Sandbox Code Playgroud)
所以现在我们可以回到视图控制器并使用一个ArrowLayer作为图像视图的掩码:
- (void)setUpMask {
arrowLayer = [ArrowLayer layer];
arrowLayer.frame = imageView.bounds;
arrowLayer.thickness = 60;
arrowLayer.startRadians = -M_PI_2;
arrowLayer.lengthRadians = 0;
arrowLayer.headLengthRadians = M_PI_2 / 8;
arrowLayer.fillColor = [UIColor whiteColor];
imageView.layer.mask = arrowLayer;
}
Run Code Online (Sandbox Code Playgroud)
我们可以将lengthRadians属性设置为0到2π的动画:
- (IBAction)goButtonWasTapped:(UIButton *)goButton {
goButton.hidden = YES;
[CATransaction begin]; {
[CATransaction setAnimationDuration:2];
[CATransaction setCompletionBlock:^{
goButton.hidden = NO;
}];
CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"lengthRadians"];
animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear];
animation.autoreverses = YES;
animation.fromValue = @0.0f;
animation.toValue = @((CGFloat)(2.0f * M_PI));
[arrowLayer addAnimation:animation forKey:animation.keyPath];
} [CATransaction commit];
}
Run Code Online (Sandbox Code Playgroud)
我们得到一个无故障的动画:

我使用Core Animation工具在运行iOS 6.0.1的iPhone 4S上对此进行了分析.它似乎每秒可以获得40-50帧.你的旅费可能会改变.我尝试打开该drawsAsynchronously属性(iOS 6中的新功能),但它没有任何区别.
我已将此答案中的代码上传为易于复制的要点.
| 归档时间: |
|
| 查看次数: |
3850 次 |
| 最近记录: |