以编程方式为iOS制作带有名称缩写的图像,如Swift中的Gmail

时间:2015-12-05 07:33:06

标签: ios swift

我需要在UITableView中显示与其姓名相对应的每个用户的个人资料照片。在下载图像之前,我需要在GMail应用程序中显示带有他名字的第一个字母的图像。如何在Swift for iOS中以编程方式执行此操作?

enter image description here enter image description here

9 个答案:

答案 0 :(得分:12)

enter image description here

"不需要任何框架"

"它的工作非常好"

@IBOutlet weak var IBtxtFieldName:UITextField!
@IBOutlet weak var IBtxtFieldSurname:UITextField!
@IBOutlet weak var IBImgViewUserProfile:UIImageView!


@IBAction func IBbtnShowTapped(sender: UIButton)
{
    let lblNameInitialize = UILabel()
    lblNameInitialize.frame.size = CGSize(width: 100.0, height: 100.0)
    lblNameInitialize.textColor = UIColor.whiteColor()
    lblNameInitialize.text = String(IBtxtFieldName.text!.characters.first!) + String(IBtxtFieldSurname.text!.characters.first!)
    lblNameInitialize.textAlignment = NSTextAlignment.Center
    lblNameInitialize.backgroundColor = UIColor.blackColor()
    lblNameInitialize.layer.cornerRadius = 50.0

    UIGraphicsBeginImageContext(lblNameInitialize.frame.size)
    lblNameInitialize.layer.renderInContext(UIGraphicsGetCurrentContext()!)
    IBImgViewUserProfile.image = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
}

" SWIFT 3.0"

@IBAction func IBbtnShowTapped(sender: UIButton)
{
    let lblNameInitialize = UILabel()
    lblNameInitialize.frame.size = CGSize(width: 100.0, height: 100.0)
    lblNameInitialize.textColor = UIColor.white
    lblNameInitialize.text = String(IBtxtFieldName.text!.characters.first!) + String(IBtxtFieldSurname.text!.characters.first!)
    lblNameInitialize.textAlignment = NSTextAlignment.center
    lblNameInitialize.backgroundColor = UIColor.black
    lblNameInitialize.layer.cornerRadius = 50.0

    UIGraphicsBeginImageContext(lblNameInitialize.frame.size)
    lblNameInitialize.layer.render(in: UIGraphicsGetCurrentContext()!)
    IBImgViewUserProfile.image = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
}

答案 1 :(得分:11)

这非常适合UIImageView:https://github.com/bachonk/UIImageView-Letters。基本上,它创建一个UIImage,在中心,输入的第一个和最后一个单词的首字母。背景颜色可以是随机的或分配的。

以下是此类别可以执行的操作的示例: enter image description here

[编辑]

您可能还想查看一下:https://github.com/bofiaza/IPImage

答案 2 :(得分:5)

使用FredLoh的建议:

我在故事板中创建了一个UILabel(nameInitialLabel)。调整了它的尺寸和字体。

func setDefaultImage(name: String) {
    nameInitialLabel.text = String(name[name.startIndex])
    nameInitialLabel.backgroundColor = pickColor(name[name.startIndex])
    nameInitialLabel.enabled = true
}

func pickColor(alphabet: Character) -> UIColor {
    let alphabetColors = [0x5A8770, 0xB2B7BB, 0x6FA9AB, 0xF5AF29, 0x0088B9, 0xF18636, 0xD93A37, 0xA6B12E, 0x5C9BBC, 0xF5888D, 0x9A89B5, 0x407887, 0x9A89B5, 0x5A8770, 0xD33F33, 0xA2B01F, 0xF0B126, 0x0087BF, 0xF18636, 0x0087BF, 0xB2B7BB, 0x72ACAE, 0x9C8AB4, 0x5A8770, 0xEEB424, 0x407887]
    let str = String(alphabet).unicodeScalars
    let unicode = Int(str[str.startIndex].value)
    if 65...90 ~= unicode {
        let hex = alphabetColors[unicode - 65]
        return UIColor(red: CGFloat(Double((hex >> 16) & 0xFF)) / 255.0, green: CGFloat(Double((hex >> 8) & 0xFF)) / 255.0, blue: CGFloat(Double((hex >> 0) & 0xFF)) / 255.0, alpha: 1.0)
    }
    return UIColor.blackColor()
}

我从https://github.com/uttesh/ngletteravatar

中提取了alphabetColors映射数组

答案 3 :(得分:2)

here添加代码。 我建议你也添加SnapKit

添加此代码,但是您正在生成单元格:

let profileView = UIView()
cell.addSubview(profileView)
profileView.snp_makeConstraints { (make) -> Void in
    make.left.equalTo(cell).offset(10)
    make.centerY.equalTo(cell)
    make.height.width.equalTo(30)
//Your color
profileView.backgroundColor = UIColor.greenColor()
let firstLetter = UILabel()
profileView.addSubview(firstLetter)
firstLetter.text = yourString[0]
//Add constraint for it, I suggest using SnapKit in which case
firstLetter.snp_makeConstraints { (make) -> Void in
     make.center.equalTo(profileView)
}

答案 4 :(得分:1)

您可以使用https://github.com/bofiaza/IPImage,但是必须对功能generateImage()进行一些更正。

在源文件中更改此代码:

public func generateImage() -> UIImage? {

    let view = setupView()

    UIGraphicsBeginImageContextWithOptions(view.bounds.size, false, 0.0)
    view.drawHierarchy(in: view.bounds, afterScreenUpdates: true)
    let image = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    print(image ?? "No image")
    return image
}

关于此:

public func generateImage() -> UIImage? {

    let view = setupView()

    UIGraphicsBeginImageContextWithOptions(view.bounds.size, false, 0.0)
    defer { UIGraphicsEndImageContext() }
    guard let currentContext = UIGraphicsGetCurrentContext() else {
        return nil
    }
    view.layer.render(in: currentContext)
    let image = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    print(image ?? "No image")
    return image
}

它将正常工作!

答案 5 :(得分:0)

我为此编写了一个Swift库: https://github.com/ayushn21/AvatarImageView

它具有高度可定制性,并使用面向协议的方法来获取数据和配置

答案 6 :(得分:0)

简单的扩展名,可以根据需要自定义。

public extension UIImageView {

    func addInitials(first: String, second: String) {
        let initials = UILabel(frame: CGRect(x: 0, y: 0, width: self.bounds.width, height: self.bounds.height))
        initials.center = CGPoint(x: self.bounds.width / 2, y: self.bounds.height / 2)
        initials.textAlignment = .center
        initials.text = first + " " + second
        initials.textColor = .black
        self.addSubview(initials)
    }
}

答案 7 :(得分:0)

已更新:

     func imageWith(name: String?) -> UIImage? {
        let frame = CGRect(x: 0, y: 0, width: 50, height: 50)
        let nameLabel = UILabel(frame: frame)
        nameLabel.textAlignment = .center
        nameLabel.backgroundColor = .lightGray
        nameLabel.textColor = .white
        nameLabel.font = UIFont.boldSystemFont(ofSize: 20)
        var initials = ""
        if let initialsArray = name?.components(separatedBy: " ") {
            if let firstWord = initialsArray.first {
                if let firstLetter = firstWord.first {
                    initials += String(firstLetter).capitalized }
            }
            if initialsArray.count > 1, let lastWord = initialsArray.last {
                if let lastLetter = lastWord.first { initials += String(lastLetter).capitalized
                }
            }
        } else {
            return nil
        }
        nameLabel.text = initials
        UIGraphicsBeginImageContext(frame.size)
        if let currentContext = UIGraphicsGetCurrentContext() {
            nameLabel.layer.render(in: currentContext)
            let nameImage = UIGraphicsGetImageFromCurrentImageContext()
            return nameImage
        }
        return nil
    }

Reference

答案 8 :(得分:0)

我更新了 Manav 的回答

    func imageWith(name: String?) -> UIImage? {
        let frame = CGRect(x: 0, y: 0, width: 50, height: 50)
        let nameLabel = UILabel(frame: frame)
        nameLabel.textAlignment = .center
        nameLabel.backgroundColor = .lightGray
        nameLabel.textColor = .darkGray
        nameLabel.font = UIFont.boldSystemFont(ofSize: 20)
        guard let initialsArray = name?.components(separatedBy: " "),
              initialsArray.count > 1,
              let firstWord = initialsArray.first,
              let firstLetter = firstWord.first,
              let lastWord = initialsArray.last,
              let lastLetter = lastWord.first else { return nil }
        nameLabel.text = "\(firstLetter.uppercased())\(lastLetter.uppercased())"
        UIGraphicsBeginImageContext(frame.size)
        if let currentContext = UIGraphicsGetCurrentContext() {
            nameLabel.layer.render(in: currentContext)
            let nameImage = UIGraphicsGetImageFromCurrentImageContext()
            return nameImage
        }
        return nil
     }