Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to draw an oval speech bubble programmatically on iPhone?

The technique shown in a similar question is a rectangular bubble. How to draw one in an oval shape? i.e.:

   enter image description here

like image 685
ohho Avatar asked Sep 22 '11 03:09

ohho


1 Answers

I would do it in two iterations.
First get the context and begin a path. Fill an ellipse and then a custom path that encloses a triangle with three lines. I assumed the following dimensions: 70 width, 62 height. Override draw rect in a subclass of UIView and instantiate in a subclassed UIViewController:

-(void)drawRect:(CGRect)rect {
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    CGContextSetRGBFillColor(ctx, 0.0, 0.0, 1.0, 1.0);
    CGContextFillEllipseInRect(ctx, CGRectMake(0.0, 0.0, 70.0, 50.0)); //oval shape
    CGContextBeginPath(ctx);
    CGContextMoveToPoint(ctx, 8.0, 40.0);
    CGContextAddLineToPoint(ctx, 6.0, 50.0);
    CGContextAddLineToPoint(ctx, 18.0, 45.0);
    CGContextClosePath(ctx);
    CGContextFillPath(ctx);
}

Produces this in the iPhone simulator when added against a gray backdrop:

enter image description here

This second code example will almost duplicate what you produced above. I implemented this using flexible sizes that could be supplied to the UIView frame when you instantiate it. Essentially, the white portion of the speech bubble is drawn with a black stroke over lay to follow.

-(void)drawRect:(CGRect)rect {
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    CGRect aRect = CGRectMake(2.0, 2.0, (self.bounds.size.width * 0.95f), (self.bounds.size.width * 0.60f)); // set the rect with inset.
    CGContextSetRGBFillColor(ctx, 1.0, 1.0, 1.0, 1.0); //white fill
    CGContextSetRGBStrokeColor(ctx, 0.0, 0.0, 0.0, 1.0); //black stroke
    CGContextSetLineWidth(ctx, 2.0); 


    CGContextFillEllipseInRect(ctx, aRect); 
    CGContextStrokeEllipseInRect(ctx, aRect);    

    CGContextBeginPath(ctx);
    CGContextMoveToPoint(ctx, (self.bounds.size.width * 0.10), (self.bounds.size.width * 0.48f));
    CGContextAddLineToPoint(ctx, 3.0, (self.bounds.size.height *0.80f));
    CGContextAddLineToPoint(ctx, 20.0, (self.bounds.size.height *0.70f));
    CGContextClosePath(ctx);
    CGContextFillPath(ctx);

    CGContextBeginPath(ctx);
    CGContextMoveToPoint(ctx, (self.bounds.size.width * 0.10), (self.bounds.size.width * 0.48f));
    CGContextAddLineToPoint(ctx, 3.0, (self.bounds.size.height *0.80f));
    CGContextStrokePath(ctx);

    CGContextBeginPath(ctx);
    CGContextMoveToPoint(ctx, 3.0, (self.bounds.size.height *0.80f));
    CGContextAddLineToPoint(ctx, 20.0, (self.bounds.size.height *0.70f));
    CGContextStrokePath(ctx);
 }

enter image description here

like image 98
samfu_1 Avatar answered Sep 20 '22 08:09

samfu_1