移动一个UIImageView
沿着点阵移动图像的最佳方法是什么?
我推荐的做法是将UIImage包装在UIImageView中,并使用CAKeyframeAnimation沿着通过以下三点的path对UIImageView的图层进行animation处理:
UIImage *image = [UIImage imageNamed:@"image.png"]; imageView = [[UIImageView alloc] initWithImage:image]; [mainView addSubview:imageView]; // Remember to remove the image view and release it when done with it CAKeyframeAnimation *pathAnimation = [CAKeyframeAnimation animationWithKeyPath:@"position"]; pathAnimation.duration = 1.0f; pathAnimation.calculationMode = kCAAnimationPaced; pathAnimation.fillMode = kCAFillModeForwards; pathAnimation.removedOnCompletion = NO; CGMutablePathRef pointPath = CGPathCreateMutable(); CGPathMoveToPoint(pointPath, NULL, viewOrigin.x, viewOrigin.y); CGPathAddLineToPoint(pointPath, NULL, point1.x, point1.y); CGPathAddLineToPoint(pointPath, NULL, point2.x, point2.y); CGPathAddLineToPoint(pointPath, NULL, point3.x, point3.y); pathAnimation.path = pointPath; CGPathRelease(pointPath); [imageView.layer addAnimation:pathAnimation forKey:@"pathAnimation"];
请注意,默认情况下,图层的位置位于图层的中心。 如果要将图层相对于另一个参考点移动,可以将图层的anchorPoint属性设置为其左上angular(iPhone上)的(0.0,0.0)或(0.0,1.0)下的剩下。
此外,这不会改变UIImageView的框架,所以如果你稍后再引用这个框架,你可能需要考虑这一点,或者在animation结束时添加一个委托方法callback来设置它到适当的价值。
通过用CGPathAddCurveToPoint()replace对CGPathAddLineToPoint()的调用,也可以使图像沿着曲线而不是直线移动。
编辑(5/14/2009):我添加了缺less的pathAnimation.path = pointPath行,并改变了错误的引用curvePath到pointPath。
最简单的方法是使用UIViewanimation
一个快速的例子,假设你能够使用UIImageView来保存图像和NSArray来保持你的观点。
UIImage *image = [UIImage imageNamed:@"image.png"]; UIImageView *imageView = [[UIImageView alloc] initWithImage:image]; [someView addSubview:imageView]; // Assume someView exists NSValue *firstPoint = [NSValue valueWithCGPoint:CGPointMake(0, 0)]; NSValue *secondPoint = [NSValue valueWithCGPoint:CGPointMake(100, 0)]; NSValue *thirdPoint = [NSValue valueWithCGPoint:CGPointMake(100, 100)]; // And so on.... NSArray *points = [NSArray arrayWithObjects:firstPoint, secondPoint, thirdPoint, nil]; for (NSValue *pointValue in points) { [UIView beginAnimations:@"UIImage Move" context:NULL]; CGPoint point = [pointValue CGPointValue]; CGSize size = imageView.frame.size; imageView.frame = CGRectMake(point.x, point.y, size.width, size.height); [UIView commitAnimations]; }