使用蒙版动画UIImageView(带蒙版的核心动画)

时间:2012-03-23 04:34:41

标签: ios core-animation core-graphics

我在UIImageView中有一个UIImage(图像上的对象)。它需要动画到右边,但这个动画需要用这个圆形蒙版掩盖。 enter image description here

我目前的代码是:

CGMutablePathRef path = CGPathCreateMutable();

CGPathAddArc(path, NULL, 44, 44, 21, 0, 2 * M_PI, NO);

CAShapeLayer *shapeLayer = [[CAShapeLayer alloc] init];
[shapeLayer setPath:path];
[shapeLayer setFillColor:[[UIColor blackColor] CGColor]];
[shapeLayer setBounds:CGRectMake(0, 0, 44, 44)];
[shapeLayer setPosition:CGPointMake(0, 0)];

UIImageView *loadingShape = [[UIImageView alloc] initWithFrame:CGRectMake(6.5, 7.5, 89, 40)];
[loadingShape setImage:[UIImage imageNamed:@"object_image.png"]];
[self addSubview:loadingShape];
// Set the mask for the image view's layer
[[loadingShape layer] setMask:shapeLayer];

[UIView beginAnimations:nil context:nil];
[UIView setAnimationCurve: UIViewAnimationCurveEaseOut];
[UIView setAnimationDuration:0.3];
[UIView setAnimationRepeatCount:10];
[loadingShape setFrame:CGRectMake(0, 7.5, 89, 40)];
[UIView commitAnimations];

但这会激活我的整个UIImageView蒙版。我需要屏蔽是静态的,只需要后面的对象来动画。

制作此产品的最佳解决方案是什么?

2 个答案:

答案 0 :(得分:4)

遮罩层shapeLayer就好像它是另一个层[loadingShape layer]的子级一样。当父图层移动时,子图形随之移动。

除了当前的动画,您还必须以相反的方向为shapeLayer设置动画。

修改:由-[UIView beginAnimations:context:]建立的动画不会自动应用于裸CALayer,因此请手动设置动画。

CGPoint p = /* you decide the new position of the shapeLayer */;
CABasicAnimation* anim = [[CABasicAnimation alloc] init];
anim.toValue = [NSValue valueWithCGPoint:p];
anim.keyPath = @"position";
anim.timingFunction = [CAMediaTimingFunction functionWithName:@"easeOut"];
anim.duration = 0.3;
anim.repeatCount = 10;
[shapeLayer.mask addAnimation:anim forKey:nil];
[anim release];

答案 1 :(得分:2)

感谢Kurt,我对我的代码进行了一些改进,得到了我喜欢的东西:)

  

CGMutablePathRef path = CGPathCreateMutable();

CGPathAddArc(path, NULL, 44, 44, 21, 0, 2 * M_PI, NO);

CAShapeLayer *shapeLayer = [[CAShapeLayer alloc] init];
[shapeLayer setPath:path];
[shapeLayer setFillColor:[[UIColor blackColor] CGColor]];
[shapeLayer setBounds:CGRectMake(0, 0, 44, 44)];
[shapeLayer setPosition:CGPointMake(0, 0)];

UIView *loadingView = [[UIView alloc] initWithFrame:CGRectMake(6.5, 7.5, 44, 44)];

UIImageView *loadingShape = [[UIImageView alloc] initWithFrame:CGRectMake(0, 18, 89, 40)];
[loadingShape setImage:[UIImage imageNamed:@"object_image.png"]];
[[loadingView layer] setMask:shapeLayer];
[loadingView addSubview:loadingShape];
[self addSubview:loadingView];
// Set the mask for the image view's layer

CABasicAnimation* anim = [[CABasicAnimation alloc] init];
anim.fromValue = [NSValue valueWithCGPoint:CGPointMake(0, 18)];
anim.toValue = [NSValue valueWithCGPoint:CGPointMake(15, 18)];
anim.keyPath = @"position";
anim.timingFunction = [CAMediaTimingFunction functionWithName:@"linear"];
anim.duration = 0.3;
anim.repeatCount = 100000;
[[loadingShape layer] addAnimation:anim forKey:nil];