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. So how to add badges on UIImageView in TableViewCell in Swift
Asked
Active
Viewed 5,179 times
3 Answers
5
You can add Badge on UIImageView this way
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

swiftBoy
- 35,607
- 26
- 136
- 135
0
RDC's answer in 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
}

Mario Steingruber
- 713
- 7
- 10