本文是关于iOS代码画气泡,手把手教你画一个气泡,其他形状请读者自行尝试,希望大家玩的开心!

//
//  SpeechBubbleView.m
//  demo
//
//  Created by mygame on 15/3/4.
//  Copyright (c) 2015年 mygame. All rights reserved.
//

#import "SpeechBubbleView.h"
#import <CoreGraphics/CoreGraphics.h>

#define kPopupTriangleHeigh 12
#define kPopupTriangleWidth 22
#define kBorderOffset       0//0.5f
@implementation SpeechBubbleView
- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = [UIColor purpleColor];
    }
    return self;
}

- (void)drawRect:(CGRect)rect {
    [super drawRect:rect];
    
    CGFloat viewW = rect.size.width;
    CGFloat viewH = rect.size.height;
    
    CGFloat strokeWidth = 1;
    CGFloat borderRadius = 10;
    CGFloat offset = strokeWidth + kBorderOffset;
    
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetLineJoin(context, kCGLineJoinRound); // 
    CGContextSetLineWidth(context, strokeWidth); // 设置画笔宽度
    CGContextSetStrokeColorWithColor(context, [UIColor lightGrayColor].CGColor); // 设置画笔颜色
    CGContextSetFillColorWithColor(context, [UIColor lightGrayColor].CGColor); // 设置填充颜色
    
    // 画三角形
    /*
     ---\/
     */
  /*
    画红色部分
  */
    CGContextBeginPath(context);
    CGContextMoveToPoint(context, borderRadius+offset, viewH-kPopupTriangleHeigh-offset);
    CGContextAddLineToPoint(context, round((viewW-kPopupTriangleWidth)/ 2.0f) + offset, viewH-kPopupTriangleHeigh-offset);
    CGContextAddLineToPoint(context, round(viewW/2.0f), viewH-offset);
    CGContextAddLineToPoint(context, round((viewW+kPopupTriangleWidth)/2.0f)+offset, viewH-kPopupTriangleHeigh-offset);
  
    // 画其余部分
  /*
 
  

  */ CGContextAddArcToPoint(context, viewW-offset, viewH-kPopupTriangleHeigh-offset, viewW-offset, kPopupTriangleHeigh+offset, borderRadius-strokeWidth); CGContextAddArcToPoint(context, viewW-offset, offset, viewW-borderRadius-offset, offset, borderRadius-strokeWidth); CGContextAddArcToPoint(context, offset, offset, offset, borderRadius+offset, borderRadius-strokeWidth); CGContextAddArcToPoint(context, offset, viewH-kPopupTriangleHeigh-offset, borderRadius+offset, viewH-kPopupTriangleHeigh-offset, borderRadius-strokeWidth); CGContextClosePath(context); CGContextDrawPath(context, kCGPathFillStroke); } @end

关于CGContextAddArcToPoint接口解释请点击这里