【问题标题】:How to make image view round in swift 4如何在swift 4中使图像视图变圆
【发布时间】:2018-04-12 07:42:10
【问题描述】:

虽然网上有这个问题的解决方案,但我做不到,我想对图像进行四舍五入。

我正在使用的这段代码:

extension UIImageView {        
    func makeRounded() {
        let radius = self.frame.width/2.0
        self.layer.cornerRadius = radius
        self.layer.masksToBounds = true
    }
 }

然后我在 viewdidload() 中调用这个函数,如 imgvw.makeRounded()。但它不会来。请帮忙

上一个链接对我没有帮助

【问题讨论】:

  • 调用viewdidappear并检查一次
  • 设置self.clipToBounds=true
  • 在你的 viewDidLayoutSubView 方法中调用这个函数
  • 可能 frame.width = 0 -> 半径 = 0,让我们在 viewdidappear 或 viewDidLayoutSubView 中调用

标签: ios swift uiimageview uiimage swift4


【解决方案1】:
import UIKit

class ViewController: UIViewController {
  @IBOutlet weak var image: UIImageView!

  func makeRounded() {

    image.layer.borderWidth = 1
    image.layer.masksToBounds = false
    image.layer.borderColor = UIColor.blackColor().CGColor
    image.layer.cornerRadius = image.frame.height/2 //This will change with corners of image and height/2 will make this circle shape
    image.clipsToBounds = true
}

快乐编码

【讨论】:

  • 它不会来,先生
  • 您是否更改了cornerRadius 的值,比如说设置.cornerRadius = 4.0。只需尝试根据您的需要更改此值
  • 它即将到来,先生,我想要圆形
  • 是的......它来了,先生
  • 问题是关于图像本身,而不是关于它何时添加到控制器
【解决方案2】:

覆盖viewDidLayoutSubviews 将不必要地调用函数makeRounded(),因为每次在超级视图中发生某些布局时都会调用它。你应该使用这个:

class RoundedImageView: UIImageView {

    @override func layoutSubviews() {
        super.layoutSubviews()
        let radius = self.frame.width/2.0
        layer.cornerRadius = radius
        clipsToBounds = true // This could get called in the (requiered) initializer
        // or, ofcourse, in the interface builder if you are working with storyboards
    }

}

将 imageView 的类设置为 RoundedImageView

【讨论】:

  • 它不会来,先生
  • @GoribDeveloper 如果您完全复制粘贴此代码!并且!将你的 UIImageView 的类设置为 RoundedImageView,它应该被四舍五入
【解决方案3】:

我的代码运行良好。

avatar.layer.borderWidth = 1
avatar.layer.masksToBounds = false
avatar.layer.borderColor = UIColor(hexString: "#39B44E").cgColor
avatar.layer.cornerRadius = avatar.frame.height/2 //This will change with corners of image and height/2 will make this circle shape
avatar.clipsToBounds = true

【讨论】:

    【解决方案4】:

    为你的班级创建一个扩展

    extension ViewController: UIViewController{
    
        func makeRounded() {
    
            layer.borderWidth = 1
            layer.masksToBounds = false
            layer.borderColor = UIColor.blackColor().CGColor
            layer.cornerRadius = frame.height/2 
            clipsToBounds = true
        }
    
    }
    

    然后调用使用它

    imageView.makeRounded()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-11-27
      • 2018-09-26
      • 1970-01-01
      • 2017-09-20
      • 1970-01-01
      • 2021-12-10
      相关资源
      最近更新 更多