iOS开发笔记--UIBezierPath画气泡

版权声明:本文为博主原创文章,未经博主同意不得转载。 https://blog.csdn.net/iDivines/article/details/87945135

重写drawRect方法画气泡

- (void)drawRect:(CGRect)rect{
    //气泡箭头的高度
    CGFloat arrowHeight = 8;
    //气泡圆角
    CGFloat cornerRadius = 4;
    
    CGFloat width = self.bounds.size.width;
    CGFloat height = self.bounds.size.height;
    //气泡开始的位置
    CGPoint point = CGPointMake(0,0);
    UIColor *bgColor = [UIColor colorWithHex:0x565656];
    //使用UIBezierPath描绘气泡形状
    UIBezierPath *path = [UIBezierPath bezierPath];
    path.lineWidth = 1;
    path.lineCapStyle = kCGLineCapRound;
    path.lineJoinStyle = kCGLineJoinRound;
    [path moveToPoint:CGPointMake(cornerRadius, arrowHeight)];
    [path addLineToPoint:CGPointMake(point.x - arrowHeight, arrowHeight)];
    [path addLineToPoint:CGPointMake(point.x, 0)];
    [path addLineToPoint:CGPointMake(point.x + arrowHeight, arrowHeight)];
    [path addArcWithCenter:CGPointMake(width - cornerRadius, cornerRadius + arrowHeight) radius:cornerRadius startAngle:M_PI * 3/2 endAngle:M_PI * 2 clockwise:YES];
    [path addArcWithCenter:CGPointMake(width - cornerRadius, height- cornerRadius) radius:cornerRadius startAngle:0 endAngle:M_PI /2 clockwise:YES];
    [path addArcWithCenter:CGPointMake(cornerRadius, height - cornerRadius) radius:cornerRadius startAngle:M_PI /2 endAngle:M_PI clockwise:YES];
    [path addArcWithCenter:CGPointMake(cornerRadius, cornerRadius + arrowHeight) radius:cornerRadius startAngle:M_PI  endAngle:M_PI * 3/2 clockwise:YES];
    [path closePath];
    
    //使用context画图
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextBeginPath(context);
    CGContextAddPath(context, path.CGPath);
    [bgColor setFill];
    CGContextDrawPath(context, kCGPathFill);
}

我为什么不用layer来实现气泡 ?

我的气泡需要有阴影效果,但layer.mask不支持,基于这个原因我选择重写drawRect方法画气泡。

猜你喜欢

转载自blog.csdn.net/iDivines/article/details/87945135