[iphone] How to fill background image of an UIView

I have an UIView and I set a background image in this way:

self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"sfond-appz.png"]];

My problem is that back-image is not centered inside the view, but it's replayed some times to fill all the view. Is there a way to center image inside uiview and scretch to have screen size?

Note: I can't use UIImageView for background cause I have a scrollview.

This question is related to iphone objective-c uiview background

The answer is


You need to process the image beforehand, to make a centered and stretched image. Try this:

UIGraphicsBeginImageContext(self.view.frame.size);
[[UIImage imageNamed:@"image.png"] drawInRect:self.view.bounds];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

self.view.backgroundColor = [UIColor colorWithPatternImage:image];

For Swift 2.1 use this...

    UIGraphicsBeginImageContext(self.view.frame.size)
    UIImage(named: "Cyan.jpg")?.drawInRect(self.view.bounds)

    let image: UIImage! = UIGraphicsGetImageFromCurrentImageContext()

    UIGraphicsEndImageContext()

    self.view.backgroundColor = UIColor(patternImage: image)

The colorWithPattern: method is really for generating patterns from images. Thus, the customization you require is most likely not possible, nor is it meant to be.

Indeed you need to use a UIImageView to center and scale an image. The fact that you have a UIScrollView does not prevent this:

Make self.view a generic view, then add both the UIImageView and the UIScrollView as subviews. Make sure all is wired up correctly in Interface Builder, and make the background color of the scroll view transparent.

This is IMHO the simplest and most flexible design for future changes.


The marked answer is fine, but it makes the image stretched. In my case I had a small tile image that I wanted repeat not stretch. And the following code was the best way for me to solve the black background issue:

UIImage *tileImage = [UIImage imageNamed:@"myTileImage"];
UIColor *color = [UIColor colorWithPatternImage:tileImage];
UIView  *backgroundView = [[UIView alloc] initWithFrame:self.view.frame];
[backgroundView setBackgroundColor:color];
//backgroundView.alpha = 0.1; //use this if you want to fade it away.
[self.view addSubview:backgroundView];
[self.view sendSubviewToBack:backgroundView];

Swift 4 Solution :

@IBInspectable var backgroundImage: UIImage? {
    didSet {
        UIGraphicsBeginImageContext(self.frame.size)
        backgroundImage?.draw(in: self.bounds)
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        if let image = image{
            self.backgroundColor = UIColor(patternImage: image)
        }
    }
}

Correct way to do in Swift 4, If your frame as screen size is correct then put anywhere otherwise, important to write this in viewDidLayoutSubviews because we can get actual frame in viewDidLayoutSubviews

   override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        UIGraphicsBeginImageContext(view.frame.size)
        UIImage(named: "myImage")?.draw(in: self.view.bounds)
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()

        view.backgroundColor = UIColor.init(patternImage: image!)
    }

For Swift 3.0 use the following code:

    UIGraphicsBeginImageContext(self.view.frame.size)
    UIImage(named: "bg.png")?.drawAsPattern(in: self.view.bounds)
    let image: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
    UIGraphicsEndImageContext()
    self.view.backgroundColor = UIColor(patternImage: image)

Repeat:

UIImage *img = [UIImage imageNamed:@"bg.png"];
view.backgroundColor = [UIColor colorWithPatternImage:img];

Stretched

UIImage *img = [UIImage imageNamed:@"bg.png"];
view.layer.contents = img.CGImage;

For Swift use this...

UIGraphicsBeginImageContext(self.view.frame.size)
UIImage(named: "ImageName.png")?.draw(in: self.view.bounds)

if let image = UIGraphicsGetImageFromCurrentImageContext(){
    UIGraphicsEndImageContext()
    self.view.backgroundColor = UIColor(patternImage: image)
}else{
    UIGraphicsEndImageContext()
    debugPrint("Image not available")
 }

You can use UIGraphicsBeginImageContext method to set the size of image same that of view.

Syntax : void UIGraphicsBeginImageContext(CGSize size);

 #define IMAGE(imageName) (UIImage *)[UIImage imageWithContentsOfFile:
  [[NSBundle mainBundle] pathForResource:imageName ofType:IMAGE_TYPE_PNG]]

        UIGraphicsBeginImageContext(self.view.frame.size);
        [[UIImage imageNamed:@“MyImage.png"] drawInRect:self.view.bounds];
        UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();

    self.view.backgroundColor = [UIColor colorWithPatternImage:IMAGE(@"mainBg")];

Examples related to iphone

Detect if the device is iPhone X Xcode 8 shows error that provisioning profile doesn't include signing certificate Access files in /var/mobile/Containers/Data/Application without jailbreaking iPhone Certificate has either expired or has been revoked Missing Compliance in Status when I add built for internal testing in Test Flight.How to solve? cordova run with ios error .. Error code 65 for command: xcodebuild with args: "Could not find Developer Disk Image" Reason: no suitable image found iPad Multitasking support requires these orientations How to insert new cell into UITableView in Swift

Examples related to objective-c

Adding a UISegmentedControl to UITableView Keep placeholder text in UITextField on input in IOS Accessing AppDelegate from framework? Warp \ bend effect on a UIView? Use NSInteger as array index Detect if the device is iPhone X Linker Command failed with exit code 1 (use -v to see invocation), Xcode 8, Swift 3 ITSAppUsesNonExemptEncryption export compliance while internal testing? How to enable back/left swipe gesture in UINavigationController after setting leftBarButtonItem? Change status bar text color to light in iOS 9 with Objective-C

Examples related to uiview

How can I mimic the bottom sheet from the Maps app? UIView touch event in controller Swift addsubview and remove it Swift UIView background color opacity How do I change UIView Size? How to add constraints programmatically using Swift Load a UIView from nib in Swift Remove all constraints affecting a UIView How do I write a custom init for a UIView subclass in Swift? How to use UIVisualEffectView to Blur Image?

Examples related to background

SwiftUI - How do I change the background color of a View? Changing background color of selected item in recyclerview Android Studio Image Asset Launcher Icon Background Color Android: keep Service running when app is killed How to set a background image in Xcode using swift? CSS Background image not loading css transition opacity fade background how to set the background image fit to browser using html background:none vs background:transparent what is the difference? How to scale images to screen size in Pygame