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

Ios 背景图像垂直拉伸,但水平重复,ios,swift,Ios,Swift,目前正在使用: self.view.backgroundColor = UIColor(patternImage: UIImage(named: "background.png")!) 但问题是它在垂直和水平方向上都会重复。我试图保持水平重复,同时垂直拉伸以适应屏幕。您可以尝试将图像重新调整到帧大小,垂直拉伸,但水平方向保持相同大小,然后像当前一样设置为重复 据我所知,没有一个内置的设置,可以在一个轴上拉伸,在另一个轴上重复 代码可能如下所示: CGRect screenRect = [[UI

目前正在使用:

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

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

您可以尝试将图像重新调整到帧大小,垂直拉伸,但水平方向保持相同大小,然后像当前一样设置为重复

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

代码可能如下所示:

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


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


}
导入UIKit
@可设计的
类BackgroundImageView:UIView{
@IBInspectable var backgroundImage:UIImage{
迪塞特{
self.setNeedsDisplay()
}
}
重写func drawRect(rect:CGRect){
变量i:CGFloat=0.0
如果背景图像!=零
{

while(i*backgroundImage!.size.width)你能连接屏幕吗?还不清楚你面临的问题是什么。@LucasHuang让我们假设你在iPad上查看应用程序;视图比iPhone高很多。图像不够大,无法到达视图底部,因此它会垂直重复。我只想垂直拉伸,因为它仍然需要水平重复。你知道吗你必须调整你所使用的图像以获得你想要的图案,但这是一个难题。@fragilecat是的,这就是为什么我想看看是否有一种方法可以基本上进行纵横匹配,然后水平重复。你最终找到好的解决方案了吗?