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
}
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.
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.
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.
UIImage contains the data for an image. UIImageView is a custom view meant to display the UIImage .
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];
}
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];
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With