0

我正在尝试以编程方式实例化图像,我的最终目标是在屏幕上的不同点水平放置一系列 Empty.png。我不知道该怎么做,但首先我只是想让一个图像出现在屏幕上。这是我在 .m 文件中的代码。

- (void)drawAtPoint:(CGPoint)point {
point = CGPointMake(100.0,100.0);
UIImageView *img = [[UIImageView alloc] init];
img.image = [UIImage imageNamed:@"Empty.png"];
[self.view addSubview:img];

预先感谢您的任何帮助。

4

3 回答 3

3

You are taking an entirely wrong approach.

As a beginner, if you find yourself in drawing code (drawAtPoint:, drawInRect: etc.), you are almost certainly in the wrong place.

Especially for things like loading and displaying images, iOS does almost all the work for you, so you really don't have to draw anything yourself.

Please do not take this the wrong way, but do yourself a big favor and get a good introductory book on the subject. The books from the Big Nerd Ranch Guide series are excellent, and very well worth the money.

EDIT:

If you really do not want to get a book (please, for your own sake, get a book - I did, and I'm very glad I did), here's a quick way that should work.

You had the right idea in creating a UIImageView, but you're using it wrong.

You very probably have a UIViewController somewhere in your app. Find (or create) the - (void)viewDidLoad method, and display your image from there:

- (void)viewDidLoad
{
    UIImage *myImage = [UIImage imageNamed:@"Empty"]; //you can leave out PNG.
    UIImageView *myFirstImageView = [[UIImageView alloc] initWithImage:myImage]; //this automatically gives the UIImageView the correct height and width
    [self.view addSubview:myFirstImageView]; //That's all. UIKit will handle displaying the imageView automatically.
}

This will display the image in the upper left hand corner of the screen.

You can easily move it around by inserting the following line somewhere after UIImageView *myFirst...:

myFirstImageView.center = CGPointMake(210.0, 345.0);

Did I mention the Big Nerd Ranch books are great to learn about iOS development, and are also even fun to read?

Also, the official documentation is very good (though not as fun or easy to read, and doesn't explain as much).

于 2013-03-07T18:27:14.003 回答
0

对不起,我之前的回答是错误的。我没有意识到你确实做了drawInRect。

不要使用图像视图。在这里,您应该使用核心图形。UIImageView 对象可能会有所帮助,但只是其中的一部分。

[img drawAtPoint:point]; 

应该做的伎俩。

于 2013-03-07T18:30:23.913 回答
0

您需要设置框架:

- (void)placeImageViewAtPoint:(CGPoint)point 
{
    UIImageView *img = [[UIImageView alloc] init];
    img.image = [UIImage imageNamed:@"Empty.png"];
    img.frame.origin = point;
    [self.view addSubview:img];  
}

我没有对此进行测试,但是如果这引发了您需要的错误:

- (void)placeImageViewAtPoint:(CGPoint)point 
{
    UIImageView *img = [[UIImageView alloc] init];
    img.image = [UIImage imageNamed:@"Empty.png"];
    CGRect frame = img.frame;
    frame.origin = point;
    img.frame = frame;
    [self.view addSubview:img];  
}

并且您可能应该从 viewDidAppear 或类似方法调用此方法:

-(void)viewDidAppear
{
    CGPoint point = point = CGPointMake(100.0,100.0);
    [self placeImageViewAtPoint:point];
}
于 2013-03-07T18:34:31.580 回答