如何将 Sprite 类与 CGRect 一起使用
我对编程(尤其是 Objective-C)非常陌生,想知道如何以绘制的 CGRect 的形式移动精灵。我在绘制 CGRect 时遇到问题,并且当我尝试移动 CGRect 时陷入困境。到目前为止,这是我的代码。这段代码中有一个 sprite 类(objective-C UIView 子类)和一个视图控制器。所有这些代码显示的是我如何绘制 CGRect。任何帮助或想法将不胜感激。
//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;
}
I am very new to programming (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;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
两点
1>你还没有
在你的 init 方法中写你应该写它
2> 你给出的行
x = 150 y = 100 并且高度和宽度是 0...我认为你错误地交换了它...你图像的高度和图像的宽度现在是 0...
Two point
1> you haven't write
in your init method you should write it
2> The line
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...