I am very new to progr开发者_Python百科amming (especially objective-C) and would like to know how to move a sprite in the form of a drawn CGRect. I am having trouble drawing the CGRect, and get majorly stuck when I try to move the CGRect. Here is my code so far. There is a sprite class (objective-C UIView subclass), and a view controller in this code. All this code shows is how I drew my CGRect. Any help or ideas would be greatly appreciated.
//the Sprite.h file
@interface Sprite : UIView {
UIImage* image;
}
//the Sprite.m file
-(id)initWithFrame:(CGRect)frame {
UIImage* loadedImage = [UIImage imageNamed:@"image1.png"];
CGRect rect = CGRectMake(frame.origin.x, frame.origin.y, loadedImage.size.width, loadedImage.size.height);
self = [super initWithFrame:rect];
image = [loadedImage retain];
self.opaque = NO;
self.backgroundColor = [UIColor clearColor];
return self;
}
-(void)drawRect:(CGRect)rect {
[image drawInRect:rect];
}
//the ViewController.m file
-(void) viewWillAppear:(BOOL)animated {
// add a sprite
Sprite* mySprite = [[Sprite alloc] initWithFrame:CGRectMake(150, 100, 0, 0)];
[self.view addSubview:mySprite];
}
//the ViewController.h file
@class Sprite;
@interface Sprite2TestViewController : UIViewController {
Sprite* Sprite;
}
Two point
1> you haven't write
`if((self = [super initWithFrame:frame]))`
in your init method you should write it
2> The line
Sprite* mySprite = [[Sprite alloc] initWithFrame:CGRectMake(150, 100, 0, 0)];
you have given x = 150 y = 100 and height and width is 0... I think you swap it by mistake... you image's height and image's width is 0 right now...
精彩评论