Background image stretches vertically but repeats horizontally

Currently used:

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

But the problem is that it repeats both vertically and horizontally. I try to keep it repeating horizontally, stretching vertically to fit the screen.

+4
source share
2 answers

A subclass of UIView calls it something like BackgroundImageView or something that it overrides drawInRect this way:

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 the UIView into IB, change its class to BackgroundImageView and set backgroundImage to background.png.

+1
source

, , , , , .

, .

:

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]];

0

Source: https://habr.com/ru/post/1620912/


All Articles