iOS 画气泡(bubble)

匆匆过客 提交于 2020-02-27 09:55:39

本文是关于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接口解释请点击这里

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!