如何设置 UIButton 图像,该图像是带边框的圆形

Nir*_*avS 1 uibutton uiimage ios swift swift3

如何设置 UIButton 图像,该图像是带边框的圆形我编写了相关代码但图像没有以正确的圆形显示..这是我的代码..

    btnMyProfile.setImage(UIImage(named: "MyDefaultImg.png"), for: .normal)
    btnMyProfile.imageView?.contentMode = .scaleAspectFit
    btnMyProfile.imageView?.layer.cornerRadius = (btnMyProfile.imageView?.frame.width)! / 2
    btnMyProfile.imageView?.layer.borderColor = UIColor.blue.cgColor
    btnMyProfile.imageView?.layer.borderWidth = 2.0
Run Code Online (Sandbox Code Playgroud)

我的 o/p 看起来像这样.. 在此处输入图片说明

但我需要这样.. 在此处输入图片说明

我能做些什么来实现我想要的输出?

Anb*_*hik 5

clipsToBounds = true为您的图像视图设置

btnMyProfile.imageView.clipsToBounds = true
Run Code Online (Sandbox Code Playgroud)

或使用

btnMyProfile.imageView.layer.masksToBounds = true
Run Code Online (Sandbox Code Playgroud)

来自苹果文档

默认情况下,角半径不适用于图层内容属性中的图像;它仅适用于图层的背景颜色和边框。但是,将masksToBounds 属性设置为true 会导致内容被裁剪到圆角。

否则另一种选择使用UIBezierPath