eskimo
eskimo

Reputation: 101

Background image stretch vertically, but repeating horizontally

Currently using:

self.view.backgroundColor = UIColor(patternImage: UIImage(named: "background.png")!)

But the problem is that it repeats both vertically and horizontally. I'm trying to keep it repeating horizontally while stretching vertically to fit the screen.

Upvotes: 5

Views: 1826

Answers (2)

Dave S
Dave S

Reputation: 3468

You could try re sizing your image to the frame, stretching it vertically but leaving it the same size horizontally then set it to repeat like you currently do.

As far as I'm aware there isn't a built in setting to stretch on one axis and repeat on another.

The code might look something like this:

CGRect screenRect = [[UIScreen mainScreen] bounds];
CGFloat screenHeight = screenRect.size.height;

UIImage * targetImage = [UIImage imageNamed:@"background.png"];
UIView * yourView = [[UIView alloc] initWithFrame:CGRectMake(0.f, 0.f, targetImage.size.width, screenHeight)];

// redraw the image
UIGraphicsBeginImageContextWithOptions(yourView.frame.size, NO, 0.f);
[targetImage drawInRect:CGRectMake(0.f, 0.f, targetImage.size.width, screenHeight)];
UIImage * resultImage = UIGraphicsGetImageFromCurrentImageContext();    
UIGraphicsEndImageContext();

[self.view setBackgroundColor:[UIColor colorWithPatternImage:resultImage]];

Re-sizing the image

Getting screen size

Upvotes: 0

beyowulf
beyowulf

Reputation: 15331

Subclass UIView call it something like BackgroundImageView or something it override drawInRect thusly:

import UIKit
@IBDesignable
class BackgroundImageView: UIView {
    @IBInspectable var backgroundImage:UIImage?{
        didSet{
            self.setNeedsDisplay()
        }
    }

    override func drawRect(rect: CGRect) {
        var i:CGFloat = 0.0
        if backgroundImage != nil
        {
            while (i*backgroundImage!.size.width)<self.bounds.size.width
            {
                backgroundImage!.drawInRect(CGRect(x: i*backgroundImage!.size.width, y: 0.0, width: backgroundImage!.size.width, height: self.bounds.size.height))
                i+=1.0
            }
        }
    }


}

Drag out a UIView in IB change its class to BackgroundImageView and set the backgroundImage to background.png.

Upvotes: 1

Related Questions