2017-01-09 79 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 
相关问题