互动图像

时间:2009-07-21 16:10:19

标签: iphone

这个社区在很多方面为我提供了巨大的帮助。 第一次问题(对我来说),这是一个简单的问题。我正在以优惠的价格完成iPhone SDK的学习曲线...但每隔一段时间,我就会遇到一个问题,即尽管它很简单,但更容易询问和处理其他事情,然后花费另一个小时阅读。

我有一个2D游戏,车辆在表面上四处移动以面向行进方向。我已经确定核心动画是我最好的方法。 车辆是一个图像。它与用户输入(触摸)互动。

我是否在正确的轨道上? UIView(充当响应者),包含包含图像(来自文件)的CALayer树。 当前文件是GIF。它使框架变得容易透明,只留下车辆图像。

从UIView子类中,如何将gif图像加载到图层中?

听起来很简单,所以我想......

干杯。

2 个答案:

答案 0 :(得分:0)

有没有理由你不能简单地将UIImageView子类化来处理你的触摸方法?在我看来,使用您的图像实例化图像视图并使用重写的UIResponder方法处理车辆移动的位置以及您需要的任何其他内容比手动管理CALayer树要容易得多。

您可以使用以下内容执行此操作:

UIImage *vehicleImage = [UIImage imageNamed:@"vehicle.gif"];
VehicleImageView *vehicleView = [[[VehicleImageView alloc]
                                  initWithImage:vehicleImage] autorelease];

然后有VehicleImageView子类UIImageView:

@interface VehicleImageView : UIImageView
// Your stuff
@end

@implementation VehicleImageView
// Your stuff

// UIResponder methods
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
    // Custom implementation
}

// Other touch methods...
@end

你似乎确实走在了正确的轨道上,因为你确实需要在你车辆的视图/视图层次结构中的某个地方使用UIResponder来获取触摸方法。

更多信息:

答案 1 :(得分:0)

你正在使用Core Animation走上正轨。 CAKeyFrameAnimation具有path属性,您将广泛使用该属性。以下示例代码(未经测试)使用直线路径,但也可以使用弯曲路径:

UIImage *carImage = [UIImage imageNamed:@"car.png"];
carView = [[UIImageView alloc] initWithImage:carImage];

[mapView addSubview:carView];

CAKeyframeAnimation *carAnimation = [CAKeyframeAnimation 
    animationWithKeyPath:@"position"];

carAnimation.duration = 5.0;

// keep the car at a constant velocity
carAnimation.calculationMode = kCAAnimationPaced;

// Rotate car relative to path
carAnimation.rotationMode = kCAAnimationRotateAuto;

// Keep the final animation
carAnimation.fillMode = kCAFillModeForwards;
carAnimation.removedOnCompletion = NO;

CGMutablePathRef carPath = CGPathCreateMutable();
CGPathMoveToPoint(carPath, NULL, 0.0, 0.0);

CGPathAddLineToPoint(carPath, NULL, 100.0, 100.0);
CGPathAddLineToPoint(carPath, NULL, 100.0, 200.0);
CGPathAddLineToPoint(carPath, NULL, 200.0, 100.0);

carAnimation.path = carPath;
CGPathRelease(carPath);

[carView.layer addAnimation:carAnimation forKey:@"carAnimation"];