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

目前使用:

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

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

最佳答案 子类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.

点赞