18

Can any body tell me how can I set Image directly on UIView ? Here is my code:

 UIView *view=[[UIView alloc]init];
 [view setImage:[UIImage imageNamed:@"image.png"]];
Shilpa
  • 340
  • 1
  • 4
  • 14

6 Answers6

21
UIView *view=[[UIView alloc]initWithFrame:CGRectMake(x, y, width, height)];
[view setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"a.png"]]];

Hope this is help you.

Manoj Chandel
  • 508
  • 5
  • 12
11

This is very simple to do. Try:

UIView * view = [[UIView alloc] initWithFrame:CGRectMake(origin_x, origin_y, width, height)]; 
UIImageView * imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"a.png"]];
[view addSubview:imageView];
[imageView release];

You can also play with the UIImageView's frame property to move it around in your UIView. Hope that Helps!

msgambel
  • 7,320
  • 4
  • 46
  • 62
4

Swift version :

let view = UIView(frame: CGRectMake(0, 0, 640, 200))
view.backgroundColor = UIColor(patternImage: UIImage(named: "myImage")!)

Swift 3:

let view = UIView(frame: CGRect(x: 0, y: 0, width: 640, height: 200))
view.backgroundColor = UIColor(patternImage: UIImage(named: "myImage")!)
James Toomey
  • 5,635
  • 3
  • 37
  • 41
user3722523
  • 1,740
  • 2
  • 15
  • 27
4
   UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)];
        [imageView setImage:[UIImage imageNamed:@"320_480clouds_background.png"]];
        self.tableView.backgroundView = imageView;
        [imageView release];

Hope this help you

Marios
  • 509
  • 1
  • 7
  • 23
2

Here I am assigning the CGImage to the contents property of layer which accepts CGImage or NSImage. You can only assign CGImage or NSImage to contents property.

layerView.layer.contents = UIImage(named: "Mario.png")?.cgImage
Tom
  • 4,257
  • 6
  • 33
  • 49
Anirudha Mahale
  • 2,526
  • 3
  • 37
  • 57
  • Please provide some explanation around why your code solves the OP's problem, and why it's better than the answers already given. This may help - [answer] – Tom Feb 06 '17 at 11:48
  • 1
    I wouldn't say that it is better everyone's answer but it is just another way you can do it. – Anirudha Mahale Feb 06 '17 at 12:00
  • Even so, an explanation of how it differs would be nice. – Tom Feb 06 '17 at 12:01
  • Am assigning the CGImage to the contents property of layer which accepts CGImage or NSImage. You can only assign CGImage or NSImage to contents property. – Anirudha Mahale Feb 06 '17 at 12:05
  • This I have done using object of CALayer on the layerView which is low-level object of UIKit. – Anirudha Mahale Feb 06 '17 at 12:10
2

you can try this :

UIView *aView=[[UIView alloc]init];

UIColor *background = [[UIColor alloc] initWithPatternImage:[UIImage imageNamed:@"anImage.png"]];
aView.backgroundColor = background;
[background release];
Maulik
  • 19,348
  • 14
  • 82
  • 137