tags:

views:

64

answers:

2

How can I create and position a new imageview in objective-c?

Thanks!

I tried this but it doesnt seem to do anything...

-(void)drawStars{ //uses random numbers to display a star on screen
    //create random position
    int xCoordinate = arc4random() % 10;
    int yCoordinate = arc4random() % 10;

    UIImageView *starImgView = [[UIImageView alloc] initWithFrame:CGRectMake(xCoordinate, yCoordinate, 58, 40)]; //create ImageView 

    starImgView.image = [UIImage imageNamed:@"star.png"];


    [starImgView release];

I placed this method in my viewcontroller. I see some CG stuff do I need to import core graphics or something? (what is core graphics anyway?)

A: 

You are asking about iPhone image view. Right? Then try this

UIImageView *imgView = [[UIImageView alloc] initWithFrame:CGRectMake(10, 10, 100, 50)];

This will create an image view of 100 x 50 dimension and locating (10, 10) of parent view.

Check the reference manual for UIImageView and UIView. You can set an image by using image property of imageView.

imgView.image = [UIImage imageNamed:@"a_image.png"];

And you can use the contentMode property of UIView to configure how to fit the image in the view. For example you can use

imgView.contentMode = UIViewContentModeCenter
to place the desired image to the center of the view. The available contentModes are listed here

taskinoor
how do you define the image to be shown?Yes, Cocoa touch is iPhone only.
Also whats the limit for the position..Like whats the maximun before it goes off screen?
answer edited. hope it helps u.
taskinoor
edited my post with code that doesnt work
+1  A: 

You haven't added your view as a subview to another view, meaning it isn't in the view hierarchy.

Assuming you are doing this in a view controller, it might look something like:

[self.view addSubview: imgView];
Darryl H. Thomas
yay it works! !