背景图像垂直拉伸,但水平重复

时间:2015-12-19 19:07:45

标签: ios swift

目前正在使用:

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

但问题是它在垂直和水平方向都重复。我试图保持水平重复,同时垂直拉伸以适应屏幕。

2 个答案:

答案 0 :(得分:1)

子类UIView称它为BackgroundImageView或者它覆盖drawInRect的东西:

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
            }
        }
    }


}

拖出IB中的UIView,将其类更改为BackgroundImageView,并将backgroundImage设置为background.png。

答案 1 :(得分:0)

您可以尝试重新调整图像的大小,垂直拉伸,但水平保持相同的大小,然后将其设置为像目前那样重复。

据我所知,没有内置设置可以在一个轴上拉伸而在另一个轴上重复。

代码可能如下所示:

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