【问题标题】:How to draw a circular UIImage on Core Graphics如何在 Core Graphics 上绘制圆形 UIImage
【发布时间】:2017-01-09 10:44:55
【问题描述】:

在自定义UIView 中,我已经覆盖了draw() 函数。我需要以圆形布局绘制图像。另外,如果可能的话,我需要调整图像的大小以保持 aspect fill/fit 属性。该怎么做?

代码:

@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 不工作。

提前致谢!

【问题讨论】:

  • cornerRadius 仅在您还设置了 masksToBounds = true 时才有效
  • @Tj3n 你的意思是 clipToBounds = true 吗?我也试过了,但没有运气。
  • iv.layer.masksToBounds = true 不起作用?它对我来说很好,也许在你的 draw 函数中你覆盖了一些东西?
  • @Tj3n 我已经发布了自定义 uiview 的完整源代码,它仍在绘制完整的矩形图像。你有什么线索吗?
  • 尝试删除iv.draw(CGRect(x: 0, y: 0, width: rect.width, height: rect.height))

标签: ios swift uiimage core-graphics uibezierpath


【解决方案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))
}

【讨论】:

  • 应用崩溃了!fatal error: init(coder:) has not been implemented:
  • 我已经编辑了答案 - 因为我在代码中动态添加了 ScoreGraphView。
  • 这有效,但仅在全视图绘制时,如果我想在大小为 (50,50) 的点 (10,10) 中绘制图像,但仍想要圆形怎么办。而且背景总是黑色的。我尝试使用 self.backgroudColor = UIColor.white & iv.backgroundColor = UIColor.clear 但没有奏效。 :(
【解决方案2】:

我终于明白了,

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)

【讨论】:

    【解决方案3】:

    请试试这个

    imageView.layer.cornerRadius = imgProfile.frame.size.height/2
    imageView.clipsToBounds = true
    

    【讨论】:

      【解决方案4】:

      这是一个 IBDesignable,您是否查看了 ScoreGraphView 故事板中的 clipsToBounds 属性?

      尝试将此添加到您的课程 ScoreGraphView 中:

      override func awakeFromNib() {
          super.awakeFromNib()
      
          self.clipsToBounds = true
          self.layer.masksToBounds = true
      }
      

      【讨论】: