2017-01-09 75 views
-1

內部自定義UIView,我已經覆蓋draw()函數。我需要在圓形佈局中繪製圖像。另外,如果可能的話,我需要調整圖片的大小以保持方面的填充/適合屬性。怎麼做?如何在Core Graphics上繪製圓形UIImage

代碼:

@IBDesignable class ScoreGraphView: UIView { 

    override func draw(_ rect: CGRect) { 

     let iv = UIImageView(image: UIImage(named: "women")) 
     iv.frame = CGRect(x: 0, y: 0, width: rect.width, height: rect.height) 
     iv.layer.cornerRadius = 20 
     iv.clipsToBounds = true 
     iv.layer.masksToBounds = true 
     iv.backgroundColor = UIColor.clear 
     iv.draw(CGRect(x: 0, y: 0, width: rect.width, height: rect.height)) 
    } 
} 

這上面的行可以用於繪製圖像。 cornerRadius/masksToBounds不起作用。

在此先感謝!

+2

'cornerRadius'只有在你設置了'masksToBounds = true'的情況下才有效 – Tj3n

+0

@ Tj3n你的意思是clipToBounds = true?我也嘗試過,但沒有運氣。 –

+0

'iv.layer.masksToBounds = true'不起作用?它對我來說工作得很好,也許在你的'draw'函數中你重寫了一些東西? – Tj3n

回答

0

最後我得到的線索,

let userimageView : UIImageView = UIImageView(frame: rect) 
userimageView.image = UIImage(named: "women") 
userimageView.backgroundColor = UIColor.clear; 
userimageView.alpha = 1.0 
userimageView.clipsToBounds = false 
userimageView.layer.cornerRadius = 20.0 
userimageView.layer.masksToBounds = true 

self.layer.addSublayer(userimageView.layer) 
-1

這是一個IBDesignable,你看了看ScoreGraphView的故事板中的clipsToBounds屬性嗎?

嘗試增加這類ScoreGraphView還有:

override func awakeFromNib() { 
    super.awakeFromNib() 

    self.clipsToBounds = true 
    self.layer.masksToBounds = true 
} 
+0

沒有工作:( –

1

第二嘗試:

override func draw(_ rect: CGRect) { 
    layer.cornerRadius = 20 
    clipsToBounds = true 
    let iv = UIImageView(image: UIImage(named: "women")) 
    iv.frame = CGRect(x: 0, y: 0, width: rect.width, height: rect.height) 
    iv.draw(CGRect(x: 0, y: 0, width: rect.width, height: rect.height)) 
} 
+0

應用程序崩潰!,'致命錯誤:初始化(編碼器:)沒有執行:' –

+0

我編輯了我的答案 - 因爲我動態地在代碼中添加ScoreGraphView – CoderMike

+0

這可行,但只有在完整視圖中繪製時,如果我想在大小爲(50,50)的點(10,10)中繪製圖像,但仍然需要圓形,並且背景始終爲黑色,我嘗試使用self.backgroudColor = UIColor.white&iv.backgroundColor = UIColor.clear但不起作用。:( –

0

請試試這個

imageView.layer.cornerRadius = imgProfile.frame.size.height/2 
imageView.clipsToBounds = true 
相關問題