如何将圆形蒙版应用于UIImageView

时间:2016-10-30 15:46:09

标签: ios swift uiimageview uiimage calayer

我已经读过其他问题,为了将圆形蒙版应用于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
    }

}

1 个答案:

答案 0 :(得分:0)

使用:

代替clipsToBounds
self.imageView.layer.masksToBounds = true