OhDoh
OhDoh

Reputation: 433

Add image to view

How to add an image to an UIView? Here is what I tried so far:

UIView *imageHolder = [[UIView alloc] initWithFrame:CGRectMake(40, 200, 280, 192)];
UIImage *image = [UIImage imageNamed:@"bloodymoon.jpg"];
[imageHolder addSubview:image]; // Error: Incompatible pointer types
[self.mainView addSubview:imageHolder];

Upvotes: 8

Views: 32738

Answers (4)

Developer
Developer

Reputation: 99

try this instead :

//set UiView background color to orange to find out the location on screen 
UIView * view111 = [[UIView alloc ] initWithFrame:CGRectMake(50,50, 50, 50)];
view111.backgroundColor = [UIColor orangeColor];
[self.view addSubview:view111];

UIImageView *imageImg = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"water1.png"]];`
// can set position to 0,0 (origin) instead of 10,10,        
imageImg.frame = CGRectMake(10,10,30,30);
[view111 addSubview:imageImg];`

Upvotes: 3

Madhu
Madhu

Reputation: 2593

Method 1:

UIImageView *imgView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"Image.jpg"]];
imgView.frame = CGRectOffset(imgView.frame, 100, 100);
[self.view addSubview:imgView];

Method 2:

You can use the following process for xib files

Step 1:You can Drag and drop the UIImageView from show the object library (Bottom right in xib)and place on view.

Step 2:Copy the image to Xcode Project

Step 3:Select the Image from the image drop down list which is present in right top corner.

Upvotes: 4

Francescu
Francescu

Reputation: 17054

Fyi

UIImage is not a subclass of UIView. UIImage is basically the imageData.

The main way to add an image to a view is to create an imageView from an image.

UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"bloodymoon.jpg"]];
//imageView has a frame {0,0,imagewidth,imageheight}
//so just move it
imageView.frame = CGRectOffset(imageView.frame, 40, 200);
[self.mainView addSubview:imageView];

This way you manipulate less "constants" numbers.

Upvotes: 1

user529758
user529758

Reputation:

Try a UIImageView:

UIImageView *imageHolder = [[UIImageView alloc] initWithFrame:CGRectMake(40, 200, 280, 192)];
UIImage *image = [UIImage imageNamed:@"bloodymoon.jpg"];
imageHolder.image = image;
// optional:
// [imageHolder sizeToFit];
[self.mainView addSubview:imageHolder];

Upvotes: 21

Related Questions