2016-10-30 59 views
0

我已閱讀了其他問題,爲了一圓面膜應用到的UIImageView我應該這樣做:如何申請圈面膜的UIImageView

self.imageView.layer.cornerRadius = self.imageView.frame.size.width/2 
self.imageView.clipsToBounds = true 

但由於某些原因,當我這樣做,我的圖像變得隱藏。當我刪除代碼來應用蒙版時,圖像將完美顯示,但在應用蒙版後不會顯示任何內容。

我不知道這是否是由於事實的UIImageView是另一個的UIView裏面,但我不明白爲什麼這是行不通的。

這是我使用的是圖像的工作文件:

import UIKit 

class ChatViewController: UIViewController { 

    var v: ChatOverview! 

    init() { 
     super.init(nibName: nil, bundle: nil) 

     self.title = "Chat" 
     self.tabBarItem.image = UIImage(named: "Chat") 
     self.tabBarItem.title = "Chats" 
    } 

    required init?(coder aDecoder: NSCoder) { 
     super.init(coder: aDecoder) 
    } 

    override func viewDidLoad() { 
     super.viewDidLoad() 

     v = ChatOverview(
      withName: "Mariano Rajoy", 
      andImage: UIImage(named: "Rajoy")! 
     ) 
     self.view.addSubview(v) 

     NSLayoutConstraint.activate([ 
      v.centerXAnchor.constraint(equalTo: self.view.centerXAnchor), 
      v.centerYAnchor.constraint(equalTo: self.view.centerYAnchor), 
      v.widthAnchor.constraint(equalToConstant: 200), 
      v.heightAnchor.constraint(equalToConstant: 200) 
     ]) 
    } 

    override func viewDidLayoutSubviews() { 
     super.viewDidLayoutSubviews() 

     self.v.applyCircleMask() 
    } 

} 

而且ChatOverview類的定義:

import UIKit 

class ChatOverview: UIView { 

    var image: UIImage! 
    var imageView: UIImageView! 

    init (withName name: String, andImage image: UIImage) { 
     super.init(frame: CGRect(x: 0, y: 0, width: 0, height: 0)) 

     self.image = image 

     self.isOpaque = false 
     self.translatesAutoresizingMaskIntoConstraints = false 

     self.imageView = UIImageView(image: self.image) 
     self.imageView.contentMode = .scaleAspectFit 
     self.imageView.translatesAutoresizingMaskIntoConstraints = false 
     self.addSubview(imageView) 

     NSLayoutConstraint.activate([ 
      self.imageView.centerXAnchor.constraint(equalTo: self.centerXAnchor), 
      self.imageView.centerYAnchor.constraint(equalTo: self.centerYAnchor), 
      self.imageView.widthAnchor.constraint(equalTo: self.widthAnchor), 
      self.imageView.heightAnchor.constraint(equalTo: self.heightAnchor) 
     ]) 
    } 

    required init?(coder aDecoder: NSCoder) { 
     super.init(coder: aDecoder) 
    } 

    func applyCircleMask() { 
     self.imageView.layer.cornerRadius = self.imageView.frame.size.width/2.0 
     self.imageView.clipsToBounds = true 
    } 

} 
+0

可以在'self.v.applyCircleMask()'行執行之前打印'ChatOverview'的框架嗎? – alexburtnik

+0

我已經編碼了一個打印,結果給了我這個寬度和高度:Frame(1463.0,1463.0)和Layer(1463.0,1463.0)。所以imageView的框架和圖層的大小都是相同的。 –

+0

嘗試添加'view.layoutIfNeeded()'在viewDidLoad'方法 – alexburtnik

回答

0

相反clipsToBounds的,使用:

self.imageView.layer.masksToBounds = true 
+0

我剛纔試過了,但它確實是相同的。 –

+0

請檢查更新的一個 –

+0

相同,沒有工作:( –