2015-07-10 102 views
2

我想創建可調整大小的ui視圖背景。它將根據文字調整大小。我嘗試下面的代碼:調整uiview的背景圖片的大小取決於文本

let capInsetsIncoming = UIEdgeInsets(top: 17, left: 26.5, bottom: 17.5, right: 21) 
self.contentView.backgroundColor = UIColor(patternImage: UIImage(named:"profileBioBackground")!.resizableImageWithCapInsets(capInsetsIncoming)) 

結果:

enter image description here

預計:

enter image description here

這是我的背景圖片:

enter image description here

我該如何解決這個問題?

回答

1

我覺得最簡單的方法是以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) 
     ) 
    } 
} 

和故事板的設置,並將結果:

screenshot