我觉得最简单的方法是以UIImageView
为背景。还有,你必须拆分原始图像,以便可以用作可调整大小图像。
总之,这里是代码:
class ViewController: UIViewController {
@IBOutlet var contentView: UIView!
override func viewDidLoad() {
super.viewDidLoad()
contentView.backgroundColor = nil
let leftBackgroundView = UIImageView()
let rightBackgroundView = UIImageView()
let image = UIImage(named: "profileBioBackground")!
let scale = image.scale
let size = image.size
let leftRect = CGRect(
x: 0,
y: 0,
width: size.width/2 * scale,
height: size.height * scale
)
let rightRect = CGRect(
x: size.width/2 * scale,
y: 0,
width: size.width/2 * scale,
height: size.height * scale
)
leftBackgroundView.image = UIImage(
CGImage: CGImageCreateWithImageInRect(image.CGImage, leftRect),
scale: scale,
orientation: .Up
)?.resizableImageWithCapInsets(UIEdgeInsets(top: 20, left: 4, bottom: 4, right: 16))
rightBackgroundView.image = UIImage(
CGImage: CGImageCreateWithImageInRect(image.CGImage, rightRect),
scale: scale,
orientation: .Up
)?.resizableImageWithCapInsets(UIEdgeInsets(top: 20, left: 16, bottom: 4, right: 4))
leftBackgroundView.setTranslatesAutoresizingMaskIntoConstraints(false)
rightBackgroundView.setTranslatesAutoresizingMaskIntoConstraints(false)
contentView.insertSubview(leftBackgroundView, atIndex: 0)
contentView.insertSubview(rightBackgroundView, atIndex: 0)
let views = ["left": leftBackgroundView, "right": rightBackgroundView]
contentView.addConstraints(
NSLayoutConstraint.constraintsWithVisualFormat("H:|[left][right(==left)]|", options: nil, metrics: nil, views: views)
+ NSLayoutConstraint.constraintsWithVisualFormat("V:|[left]|", options: nil, metrics: nil, views: views)
+ NSLayoutConstraint.constraintsWithVisualFormat("V:|[right]|", options: nil, metrics: nil, views: views)
)
}
}
和故事板的设置,并将结果: