简体   繁体   中英

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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM