Question

I currently have an application that has a messaging feature. It allows users to chat with one another. Currently the messages appear from the bottom up (I was able to accomplish this by rotating the table and the cells). Right now to distinguish between the sender and the receiver I use different colored text.

I want to use a bubble image as a background for the messages instead so that the app looks a lot more like iMessage. I know there is away to resize an image but I cannot get my head around this. Will I need a special kind of image? If so, how can I resize that image so that it fits the text and then place it as the background?

Thanks in advance for your help.

-EDIT- Code I am using to generate the cell with the bubble:

[self.textLabel setFont:[UIFont fontWithName:@"Helvetica" size:20]];
[self.textLabel setNumberOfLines:0];
CGSize size = [message.message sizeWithFont:self.textLabel.font];

    [self.textLabel setFrame:CGRectMake(690.0f - (size.width + 5.0f), 8.0f, size.width + 5.0f, size.height)];
    UIImage *bubble = [[UIImage imageNamed:@"aqua.png"] stretchableImageWithLeftCapWidth:24 topCapHeight:15];
    UIImageView *bubbleView = [[UIImageView alloc] initWithFrame:CGRectMake(704 - (size.width + 25.0f), 2.0f, size.width + 25.0f, size.height + 15.0f)];
    bubbleView.image = bubble;
    self.backgroundColor = [UIColor clearColor];
    self.opaque = NO;
    self.backgroundView = bubbleView;
Was it helpful?

Solution

There are several ways to implement such a feature. Probably the easiest solution is using the
-resizableImageWithCapInsets: method of UIImage. You could create a tableview cell for each chat message and on the background draw this image and make the image stretch at the cap inset points.

In the tableView delegate method -tableView:heightForRowAtIndexPath: you can set the height of the cell, making use of the NSString method
-sizeWithFont:constrainedToSize:lineBreakMode: to calculate the proper height of the cell's contents (the actual chat message).

OTHER TIPS

I have created a ditto iMessage like bubble using 4 UIViews. It is available in both code and XIB (UITableViewCell). It is highly customizable. You can change the color, font, font size, tail or no tail, etc. Do check it out here

https://github.com/kerrygrover/iMessageBubble

enter image description here

Add a UIImageView to whatever object you're using to show the texts. Then just set its image property to whatever image you want; UIImageView will autoresize it for you.

UIImageView Class Reference

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top