简体   繁体   English

在Swift中,如何在TableView中的TableViewCell中添加UIImageView上的徽章?

[英]In Swift, How to add Badges on UIImageView in TableViewCell in TableView?

I am developing a social networking site where I have a TableView with multiple cells(rows), in each cell I have a "comment" and "like" Imageview, so whenever update comes from the server I have to increment the number of "comment" and "like" through badges. 我正在开发一个社交网站,我有一个带有多个单元格(行)的TableView,在每个单元格中我有一个“注释”和“喜欢”Imageview,所以每当更新来自服务器时我都要增加“注释”的数量“和”喜欢“通过徽章。 So how to add badges on UIImageView in TableViewCell in Swift 那么如何在Swift中的TableViewCell中添加UIImageView上的徽章

You can add Badge on UIImageView this way 您可以通过这种方式在UIImageView上添加徽章

func drawImageView(mainImage: UIImage, withBadge badge: UIImage) -> UIImage
{
    UIGraphicsBeginImageContextWithOptions(mainImage.size, false, 0.0)
    mainImage.drawInRect(CGRectMake(0, 0, mainImage.size.width, mainImage.size.height))
    badge.drawInRect(CGRectMake(mainImage.size.width - badge.size.width, 0, badge.size.width, badge.size.height))

    let resultImage: UIImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    return resultImage
}

and then use this function 然后使用此功能

    let mainImage = UIImage(named: "main_image_name_here")
    let badgeImage = UIImage(named: "badge_icon_name_here")
    let myBadgedImage: UIImage = drawImageView(mainImage!, withBadge: badgeImage!)
    myImageView.image = myBadgedImage//set Image on ImageView

check out this MIBadgeButton-Swift 看看这个MIBadgeButton-Swift

Good luck 祝好运

RDC's answer in SWIFT 3 RDC在SWIFT 3中的回答

func drawImageView(mainImage: UIImage, withBadge badge: UIImage) -> UIImage {
    UIGraphicsBeginImageContextWithOptions(mainImage.size, false, 0.0)
    mainImage.draw(in: CGRect(x: 0, y: 0, width: mainImage.size.width, height: mainImage.size.height))
    badge.draw(in: CGRect(x: mainImage.size.width - badge.size.width, y: 0, width: badge.size.width, height: badge.size.height))

    let resultImage: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
    UIGraphicsEndImageContext()
    return resultImage
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM