iOS 画气泡

来源:互联网 发布:尚学堂java培训怎么样 编辑:程序博客网 时间:2024/04/30 01:58

1 先自定义一个view

#import <UIKit/UIKit.h>

#define kCalloutWidth   80.0   // 气泡高度

#define kCalloutHeight  95.0     // 气泡宽度

#define kArrorHeight    15       // 底部距离高度

@interface CallOutContentView : UIView

@end

2实现代码

#import "CallOutContentView.h"

@implementation CallOutContentView

- ( instancetype )initWithFrame:( CGRect )frame {

if ( self = [ super initWithFrame :frame]) {                  

self . backgroundColor = [ UIColor clearColor ];         

}

return self ;

}

#pragma mark - draw rect

- ( void )drawRect:( CGRect )rect{  

[ self drawInContext : UIGraphicsGetCurrentContext ()];

self . layer . shadowColor = [[ UIColor clearColor ] CGColor ];

self . layer . shadowOpacity = 1.0 ;

self . layer . shadowOffset = CGSizeMake ( 0.0f , 0.0f );

}

- ( void )drawInContext:( CGContextRef )context

{  

CGContextSetLineWidth (context, 2.0 );

CGContextSetFillColorWithColor (context,  [ UIColor colorWithRed : 0.000 green : 0.251 blue : 0.502 alpha : 1.000 ]. CGColor ); //气泡填充色

[ self getDrawPath :context];

}

// 气泡背景绘制

- ( void )getDrawPath:( CGContextRef )context

{

CGRect rrect = self . bounds ;     

CGFloat radius = ( kCalloutHeight - kArrorHeight ) / 2.0 ;  

CGFloat midx = CGRectGetMidX (rrect);

CGFloat maxy = CGRectGetMaxY (rrect) - kArrorHeight ; // 调节离底部的位置

CGFloat midy = maxy / 2.0 ;

CGContextSaveGState (context); // 保存上下文 1

CGContextBeginPath (context);

// 底部三角

CGContextMoveToPoint (context, midx + kArrorHeight , maxy);

CGContextAddLineToPoint (context, midx, maxy + kArrorHeight );

CGContextAddLineToPoint (context, midx - kArrorHeight , maxy);     

CGContextFillPath (context); // 渲染三角形

CGContextRestoreGState (context); // 还原上下文 1

CGContextAddArc (context, midx, midy + 5 , radius, 0 , M_PI * 2 , 1 ); // 画圆

CGContextFillPath (context); // 渲染圆形 

CGContextClosePath (context);

}

@end

3 创建实例

CallOutContentView *callOutView = [[ CallOutContentView alloc ] initWithFrame : CGRectMake ( 0 , 0 , kCalloutWidth , kCalloutHeight )];

原文地址:http://www.tuicool.com/articles/qIr2yyF

0 0
原创粉丝点击