Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cocoa Touch - Adding a UIImageView programmatically?

Tags:

cocoa-touch

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?)

like image 391
user377419 Avatar asked Jul 23 '10 18:07

user377419


People also ask

How to add UIImageView Programmatically Swift?

First you create a UIImage from your image file, then create a UIImageView from that: let imageName = "yourImage. png" let image = UIImage(named: imageName) let imageView = UIImageView(image: image!)

How do I add an image to UIImageView?

The first step is to drag the UIImageView onto your view. Then open the UIImageView properties pane and select the image asset (assuming you have some images in your project). You can also configure how the underlying image is scaled to fit inside the UIImageView.

How do I create a UIImage?

To create a new UIImage programmatically in Swift, we simply need to create a new instance of UIImage providing it with the name of the image we have added to a Resources folder. Once we have an instance of UIImage created, we can add it to a UIImageView.

What is UIImageView?

An object that manages image data in your app.


Video Answer


2 Answers

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
like image 177
taskinoor Avatar answered Sep 29 '22 19:09

taskinoor


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];
like image 34
Darryl H. Thomas Avatar answered Sep 29 '22 18:09

Darryl H. Thomas