iOS swift:TabBarItem中标签的图像

时间:2017-10-31 13:54:24

标签: ios swift uiimage uitabbarcontroller

我试图创建一个名字首字母独立的灰色圆圈。并将其用作tabBarItem图像。

这是我用来创建圆圈的功能,它几乎可以正常工作,如下图所示,但它不是圆形的方形:

static func createAvatarWithInitials(name: String, surname: String, size: CGFloat) -> UIImage {
        let initialsLabel = UILabel()
        initialsLabel.frame.size = CGSize(width: size, height: size)
        initialsLabel.textColor = UIColor.white
        initialsLabel.text = "\(name.characters.first!)\(surname.characters.first!)"
        initialsLabel.textAlignment = .center
        initialsLabel.backgroundColor = UIColor(red: 74.0/255, green: 77.0/255, blue: 78.0/255, alpha: 1.0)
        initialsLabel.layer.cornerRadius = size/2

        let scale = UIScreen.main.scale
        UIGraphicsBeginImageContextWithOptions(initialsLabel.frame.size, false, scale)

        initialsLabel.layer.render(in: UIGraphicsGetCurrentContext()!)
        let image: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
        UIGraphicsEndImageContext()
        image.withRenderingMode(.alwaysOriginal)
        return image
}

这就是我在tabBarController的viewDidLoad中调用它的方式:

if index == positionForProfileItem {
                    tabBarItem.image = UIImage.createAvatarWithInitials(name: "John", surname: "Doe", size: CGFloat(20))
}

但我在标签栏中看到了一个空的方形矩形。我无法弄清楚原因,有什么帮助吗?

enter image description here enter image description here

2 个答案:

答案 0 :(得分:1)

UIImage withRenderingMode方法返回一个新图像。它不会修改发件人。

将最后两行更改为一行:

return image.withRenderingMode(.alwaysOriginal)

但这不是你想做的。由于您需要中间文本的圆形模板图像,因此需要执行以下操作:

static func createAvatarWithInitials(name: String, surname: String, size: CGFloat) -> UIImage {
    UIGraphicsBeginImageContextWithOptions(CGSize(width: size, height: size), false, 0)
    let ctx = UIGraphicsGetCurrentContext()!

    // Draw an opague circle
    UIColor.white.setFill()
    let circle = UIBezierPath(ovalIn: CGRect(x: 0, y: 0, width: size, height: size))
    circle.fill()

    // Setup text
    let font = UIFont.systemFont(ofSize: 17)
    let text = "\(name.characters.first!)\(surname.characters.first!)"
    let textSize = (text as NSString).size(withAttributes: [ .font: font ])

    // Erase text
    ctx.setBlendMode(.clear)
    let textRect = CGRect(x: (size - textSize.width) / 2, y: (size - textSize.height) / 2, width: textSize.width, height: textSize.height)
    (text as NSString).draw(in: textRect, withAttributes: [ .font: font ])

    let image: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
    UIGraphicsEndImageContext()

    return image
}

答案 1 :(得分:1)

你必须在你的标签上添加clipsToBounds = YES,以使cornerRadius在你的屏幕拍摄上有效,并尝试将图像的大小从20增加到30.