背景图片在垂直方向上拉伸,但在水平方向上重复。

5

目前正在使用:

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

但问题在于它在垂直和水平方向上都重复出现。我想让它在水平方向上重复出现,同时在垂直方向上拉伸以适应屏幕。


你能附上屏幕吗?不太清楚你面临的问题是什么。 - Lucas Huang
@LucasHuang 假设您正在iPad上查看应用程序;视图比iPhone高得多。该图像不足以到达视图底部,因此会在垂直方向重复。我只想在垂直方向上拉伸,因为它仍然需要在水平方向上重复。 - eskimo
你需要调整你所使用的图像来达到你想要的效果,但这是一种hack方法。 - Peter Hornsby
@fragilecat 是的,这就是为什么我想看看是否有一种方法可以基本上按比例适合并水平重复。 - eskimo
1
你最后找到了好的解决方案吗? - Nikhil Manapure
2个回答

1

创建一个名为BackgroundImageView的UIView子类,重写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。


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

调整图像大小

获取屏幕尺寸


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接