我有一个类,它有16个子层(sublayers),用来形成一个标志。当我对 UIView 进行动画处理时,CALayer 不会被动画处理,只是像下面的动态图一样直接到达最终状态:
我的代码如下:
@implementation LogoView
#define CGRECTMAKE(a, b, w, h) {.origin={.x=(a),.y=(b)},.size={.width=(w),.height=(h)}}
#pragma mark - Create Subviews
const static CGRect path[] = {
CGRECTMAKE(62.734375,-21.675000,18.900000,18.900000),
CGRECTMAKE(29.784375,-31.725000,27.400000,27.300000),
CGRECTMAKE(2.534375,-81.775000,18.900000,18.900000),
CGRECTMAKE(4.384375,-57.225000,27.400000,27.300000),
CGRECTMAKE(2.784375,62.875000,18.900000,18.900000),
CGRECTMAKE(4.334375,29.925000,27.400000,27.300000),
CGRECTMAKE(62.734375,2.525000,18.900000,18.900000),
CGRECTMAKE(29.784375,4.475000,27.400000,27.300000),
CGRECTMAKE(-21.665625,-81.775000,18.900000,18.900000),
CGRECTMAKE(-31.765625,-57.225000,27.400000,27.300000),
CGRECTMAKE(-81.615625,-21.425000,18.900000,18.900000),
CGRECTMAKE(-57.215625,-31.775000,27.400000,27.300000),
CGRECTMAKE(-81.615625,2.775000,18.900000,18.900000),
CGRECTMAKE(-57.215625,4.425000,27.400000,27.300000),
CGRECTMAKE(-21.415625,62.875000,18.900000,18.900000),
CGRECTMAKE(-31.765625,29.925000,27.400000,27.300000)
};
- (void) createSubviews
{
self.contentMode = UIViewContentModeRedraw;
for (int i = 0; i < 16; i++) {
CGRect rect = CGRectApplyAffineTransform(path[i],
CGAffineTransformMakeScale(self.frame.size.width / 213.0,
self.frame.size.height / 213.0));
UIBezierPath * b = [UIBezierPath bezierPathWithOvalInRect:
CGRectOffset(rect,
self.frame.size.width/2.0,
self.frame.size.height/2)];
CAShapeLayer * layer = [[CAShapeLayer alloc] init];
layer.path = [b CGPath];
layer.fillColor = [self.tintColor CGColor];
[self.layer addSublayer:layer];
}
self.layer.needsDisplayOnBoundsChange = YES;
self.initialLenght = self.frame.size.width;
}
- (void) layoutSublayersOfLayer:(CALayer *)layer
{
for (int i = 0; i < 16; i++) {
CGRect rect = CGRectApplyAffineTransform(path[i],
CGAffineTransformMakeScale(layer.frame.size.width / 213.0,
layer.frame.size.height / 213.0));
UIBezierPath * b = [UIBezierPath
bezierPathWithOvalInRect:CGRectOffset(rect,
layer.frame.size.width/2.0,
layer.frame.size.height/2)];
((CAShapeLayer*)(layer.sublayers[i])).path = b.CGPath;
}
}
- (void)layoutSubviews {
[super layoutSubviews];
// get current animation for bounds
CAAnimation *anim = [self.layer animationForKey:@"bounds"];
[CATransaction begin];
if(anim) {
// animating, apply same duration and timing function.
[CATransaction setAnimationDuration:anim.duration];
[CATransaction setAnimationTimingFunction:anim.timingFunction];
CABasicAnimation *pathAnimation = [CABasicAnimation animationWithKeyPath:@"path"];
[self.layer addAnimation:pathAnimation forKey:@"path"];
}
else {
// not animating, we should disable implicit animations.
[CATransaction disableActions];
}
self.layer.frame = self.frame;
[CATransaction commit];
}
我正在使用以下内容进行动画制作:
[UIView animateWithDuration:3.0 animations:^{
[v setFrame:CGRectMake(0.0, 0.0, 300.0, 300.0)];
}];
如何将图层动画与视图动画同步?
drawRect:
呢? - picciano