5

Is it possible to overlay UIView with an image without using UIImageView from the Interface Builder?

If not, how would you accomplish the same in code?

James Raitsev
  • 92,517
  • 154
  • 335
  • 470

2 Answers2

5

From the UIView documentation:

Image-based backgrounds - For views that display relatively static content, consider using a UIImageView object with gesture recognizers instead of subclassing and drawing the image yourself. Alternatively, you can also use a generic UIView object and assign your image as the content of the view’s CALayer object.

Using the second option, to set someView to have a background of yourImage.png:

someView.layer.contents = (id)[[UIImage imageNamed:@"yourImage.png"] CGImage];

dingo sky
  • 1,445
  • 17
  • 15
3

if by Overlying a UIView you mean painting its background with an image, it can be done like this:

someView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"yourImage.png"]];

You could also add a new UIImageView that covers your UIView by code, Init your UIImageView with the same frame Rect as your UIView and add it as a subview.

John Topley
  • 113,588
  • 46
  • 195
  • 237
Alon Amir
  • 4,913
  • 9
  • 47
  • 86
  • Right, because the function colorWithPatternImage is a customized method, it's not an option that appears on the IB. only single colors are there to choose from. although the same task could be done with the IB by creating a UIImageView that covers your view and has the same frame. when you don't want your view to be covered or not, you can simply set it's .hidden property to YES/NO. – Alon Amir Oct 29 '11 at 23:06
  • I would probably go for the `UIImageView` option as I'm guessing it will be more optimised than generating a pattern that Core Graphics will then have to draw after figuring out the tiling etc. – Paul.s Oct 30 '11 at 00:14