Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you create a UIImageView programmatically in Xcode

I just want to make an UIImageView programmatically that displays a 20by20 dot at point (50,50).(The image of the dot is called draw.png). For some reason nothing shows up on the screen.

Heres my code:

- (void)viewDidLoad
{
UIImageView *dot =[[UIImageView alloc] initWithFrame:CGRectMake(50,50,20,20)];
dot.image=[UIImage imageNamed:@"draw.png"];
[self.view addSubview:dot];


[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib
}
like image 908
user3143098 Avatar asked Dec 29 '13 02:12

user3143098


People also ask

How do I add a UIImage in Xcode?

Drag and drop image onto Xcode's assets catalog. Or, click on a plus button at the very bottom of the Assets navigator view and then select “New Image Set”. After that, drag and drop an image into the newly create Image Set, placing it at appropriate 1x, 2x or 3x slot.

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.

How do I add an image to UIImageView?

Since you have your bgImage assigned and linked as an IBOutlet, there is no need to initialize it as a UIImageView... instead all you need to do is set the image property like bgImage. image = UIImage(named: "afternoon") . After running this code, the image appeared fine since it was already assigned using the outlet.

What is the difference between a UIImage and a UIImageView?

UIImage contains the data for an image. UIImageView is a custom view meant to display the UIImage .


3 Answers

First, make sure draw.png exists in your project and that you are referencing it exactly (so if it's draw.PNG you should put @"draw.PNG"). Also, call [super viewDidLoad] before everything.

- (void)viewDidLoad
{
  [super viewDidLoad];
  // Do any additional setup after loading the view, typically from a nib

  UIImageView *dot =[[UIImageView alloc] initWithFrame:CGRectMake(50,50,20,20)];
  dot.image=[UIImage imageNamed:@"draw.png"];
  [self.view addSubview:dot];

}
like image 173
JuJoDi Avatar answered Jan 15 '23 10:01

JuJoDi


Try this :-

 UIImageView *imageview = [[UIImageView alloc]
 initWithFrame:CGRectMake(50, 50, 20, 20)];
 [imageview setImage:[UIImage imageNamed:@"AppleUSA1.jpg"]];
 [imageview setContentMode:UIViewContentModeScaleAspectFit];
 [self.view addSubview:imageview];
like image 31
Nilesh Parmar Avatar answered Jan 15 '23 10:01

Nilesh Parmar


In Swift :

   let imageView = UIImageView(frame: CGRect(x: 50, y: 50, width: 20, height: 20))
     imageView.image = UIImage(named: "draw.png")
     self.view.addSubview(imageView)
like image 36
chimbu Avatar answered Jan 15 '23 10:01

chimbu